안녕하세요. 블레이저를 이용해서 모바일에서 스캔을 하려고 합니다.
사용자에 대한 로그인 기능은 필요가 없어서 메일을 통해 OTP 인증을 하면 인증쿠키 (휘발성)가
발행되고 사이트 이용을 하도록 하고 싶습니다.
(추후 무단 접근을 막기 위해 브라우저 ID도 저장할 예정)
간단히 Test를 진행하고 있는데 HttpClient에서 InvalidOpertionException이 발생하면 쿠키를 발행하지 못하는데 이유가 무엇을까요?? 구현 방법이 잘못되었을까요?
Program.cs
//인증쿠키 JSP와 달리 블레이저는 세션 개념이 없다. 해서 Pricipal이란 쿠키로 세션인증을 거친다.
builder.Services.AddAuthentication("mescookie").AddCookie("mescookie" , options =>
{
options.Cookie.Name = "mescookie";
options.LoginPath = "/mes";
options.Cookie.Path = "/";
options.SlidingExpiration = false;
});
builder.Services.AddAuthorization();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddHttpClient();
builder.Services.AddScoped<HttpClient>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.MapPost("/issue-cookie", async (HttpContext context, string userId) =>
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, userId),
new Claim(ClaimTypes.Name, userId)
};
var identity = new ClaimsIdentity(claims, "mescookie");
var principal = new ClaimsPrincipal(identity);
await context.SignInAsync("mescookie", principal, new AuthenticationProperties
{
IsPersistent = false // 세션 쿠키 (브라우저 종료 시 삭제)
});
return Results.Ok();
});
app.Run();
접속 레이저 파일 일부
@inject HttpClient Http
@inject NavigationManager Navigation
private async Task confirmOTP()
{
if (string.IsNullOrEmpty(InputOtpCode) || !InputOtpCode!.Equals(OtpCode))
{
await DialogService.Alert("유효하지 않는 OTP코드입니다.", "확인!");
}
else
{
optTimer!.Stop();
optTimer.Dispose();
OtpColor = "blue";
OtpMessage = "인증되었습니다.";
await Task.Delay(500);
var result = await DialogService.OpenAsync<SaveInfo>("취급정보저장안내",null,new DialogOptions { Width="550px", Height = "auto" , ShowClose=false});
if (result)
{
//브라우저 고유 ID 불러오는 부분
//DB 저장
Console.WriteLine("DB 저장완료!");
}
/*인증세션 발급*/
_ = OnVerifiedAsync();
}
}
private async Task OnVerifiedAsync()
{
var result = await Http.PostAsJsonAsync("/issue-cookie", new { userId = "otpverified-user" });
Console.WriteLine(Http is null ? "Null" : "NO");
if (result.IsSuccessStatusCode)
{
// 쿠키 발급됨 → 페이지 새로고침해서 인증된 사용자로 전환
Navigation.NavigateTo("/counter", forceLoad: true);
}
}
현재 OnVerifiedAsync에서 Http 관련 InvalidOpertationException이 발생하는데 이유를 모르겠습니다. Program.cs에서 빌드서비스에 등록을 했고 정상적으로 inject를 했는데 Console에 아무것도 찍히 않는걸 보니 PostAs 여기에서 예외가 발생하는 것 같은데..