我在基于ASP.NET Core 6的web应用程序中实现了一个自定义身份验证方案,该应用程序具有棱角前端,如这里所描述的那样。
在我的AuthenticationHandler中,我读取了当前会话中的一些变量,为了验证用户身份,我需要这些变量。它基本上是这样工作的:
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
try
{
ISession session;
try
{
session = this.Context.Session;
}
catch (InvalidOperationException)
{
return Task.FromResult(AuthenticateResult.NoResult());
}
// Get user information from session
if (/*User information incomplete or null*/)
{
this.Logger.LogDebug("No user credentials found in session");
return Task.FromResult(AuthenticateResult.NoResult());
}
Claim[] claims = new[] {
new Claim(...),
new Claim(...) };
ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, nameof(MyAuthHandler));
AuthenticationTicket? ticket = new AuthenticationTicket(new ClaimsPrincipal(claimsIdentity), this.Scheme.Name);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
catch (Exception ex)
{
return Task.FromResult(AuthenticateResult.Fail("Check logged in exception"));
}
}当我在Kestrel中本地运行和调试应用程序时,一切正常,但是当它驻留在IIS上时,在成功登录后不能刷新页面。奇怪的是,每次使用回退路由(当路由属于角前端中的某个东西而不是后端API)时,会话都是空的。因此,当我成功地通过前端登录,然后刷新页面时,刷新就不起作用了,我得到了一个由when服务器返回的401错误。出现这种情况的一个例子是,当我登录时,被重定向到角应用程序的“仪表板”路径,然后刷新页面。然后,当我检查日志时,记录的内容如下:
INFO Microsoft.AspNetCore.Hosting.Diagnostics [(null)]: Request starting HTTP/1.1 GET http://<url>/dashboard - -
DEBUG Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware [(null)]: The request path /dashboard does not match a supported file type
DEBUG Microsoft.AspNetCore.Routing.Matching.DfaMatcher [(null)]: 1 candidate(s) found for the request path '/dashboard'
DEBUG Microsoft.AspNetCore.Routing.Matching.DfaMatcher [(null)]: Endpoint 'Fallback {**slug}' with route pattern '{**slug}' is valid for the request path '/dashboard'
DEBUG Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware [(null)]: Request matched endpoint 'Fallback {**slug}'
DEBUG MyApp.BusinessLogic.Authentication.MyAuthHandler [(null)]: No user credentials found in session
DEBUG MyApp.BusinessLogic.Authentication.MyAuthHandler [(null)]: AuthenticationScheme: MyAuthScheme was not authenticated.
INFO Microsoft.AspNetCore.Authorization.DefaultAuthorizationService [(null)]: Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.我还想指出,会话变量实际上并没有消失。当我手动导航到web应用程序的根路径时,一切都恢复正常,我仍然登录。
下面是应用程序在我的Program.cs文件中的配置方式:
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Logging.AddLog4Net();
builder.Services.AddAuthentication(MyAuthDefaults.AuthenticationScheme)
.AddScheme<MyAuthSchemeOptions, MyAuthHandler>(
MyAuthDefaults.AuthenticationScheme, options => { });
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddControllers();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromHours(8);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.Cookie.Path = "/api/";
});
WebApplication app = builder.Build();
app.UseHttpsRedirection();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Map("api/{**slug}", HandleApiFallback);
app.MapFallbackToFile("{**slug}", "index.html");
app.Run();
static Task HandleApiFallback(HttpContext context)
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
return Task.CompletedTask;
}为什么在这个场景中会话变量突然消失了,我如何解决这个问题?
发布于 2022-06-02 13:24:34
这个选项似乎引起了问题:
options.Cookie.Path = "/api/"我只是不知道为什么这只会在IIS上造成问题,而不是在本地调试应用程序时。
https://stackoverflow.com/questions/72476629
复制相似问题