该问题是由于Blazor WASM默认情况下缓存AuthenticationState的Claims,因此当用户的Claims已更改而未刷新时,将会出现Claims null的情况。要解决该问题,可以禁用Blazor的缓存功能,或者在每次更改时手动刷新AuthenticationState。
以下是禁用缓存的示例代码:
//在Startup.cs中添加以下代码 services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.Events = new JwtBearerEvents { OnTokenValidated = async ctx => { var token = ctx.SecurityToken as JwtSecurityToken; if (token != null) { //添加Claims ((ClaimsIdentity)ctx.Principal.Identity).AddClaim(new Claim("my_claim", "my_value")); } } }; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidateAudience = true, ValidAudience = Configuration["Jwt:Audience"], ValidateLifetime = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Jwt:SecretKey"])), ValidateIssuerSigningKey = true }; options.IncludeErrorDetails = true; options.RequireHttpsMetadata = false; });
//在Program.cs中添加以下代码
builder.Services.AddScoped
builder.Services.AddHttpClient("my_api", client => { client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress); }) .AddHttpMessageHandler(sp => { var stateProvider = sp.GetService(typeof(CustomAuthenticationStateProvider)) as CustomAuthenticationStateProvider;
var handler = new JwtBearerHandler(stateProvider);
handler.InnerHandler = new HttpClientHandler();
return handler;
});
以下是手动刷新AuthenticationState的示例代码:
//在CustomAuthenticationStateProvider.cs中添加以下代码 public async Task MarkUserAsAuthenticated(string token) { var handler = new JwtSecurityTokenHandler(); var jsonToken = handler.ReadToken(token); var tokenJWT =