Blazor WASM CheckSession 循环问题通常是由于在操作 Blazor WebAssembly 应用时使用了旧浏览器版本或强制刷新的情况下发生的。为了解决此问题,可以在本地存储中保留用户信息并在重启应用程序时恢复会话。以下是一个示例实现:
在 Startup.cs 文件中添加以下代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorizationCore();
// Add the authentication services
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = "https://my-auth-server.com/";
options.Audience = "my-audience";
// Add the token to the SignalR connection
options.Events = new JwtBearerEvents()
{
OnMessageReceived = context =>
{
context.Token = context.Request.Query["access_token"];
return Task.CompletedTask;
}
};
});
services.AddControllers();
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Store the user information in the local storage
app.Use(async (context, next) =>
{
var user = context.User;
if (user.Identity.IsAuthenticated)
{
var claims = new List();
claims.Add(new Claim("name", user.Identity.Name));
claims.AddRange(user.Claims);
var identity = new ClaimsIdentity(claims, "Bearer");
var principal = new ClaimsPrincipal(identity);
await context.RequestServices.GetRequiredService()
.HttpContext.Authentication.SignInAsync("Bearer", principal);
}
await next.Invoke();
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSpaStaticFiles();
app.UseSpa(spa =>
{
spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions