我正在开发一个使用 JWT 身份验证/授权的
Blazor WebAssembly
托管应用程序。当我运行该项目并尝试注册或登录时,我收到以下信息日志,表明用户因未经身份验证而被拒绝访问:
我应该如何处理这个错误?
// ConfigureServices
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(Configuration["jwt:key"])),
ClockSkew = TimeSpan.Zero
}); ;
// 配置方法
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages().RequireAuthorization();
endpoints.MapControllers().RequireAuthorization();
endpoints.MapFallbackToFile("index.html");
});
}
我不知道它到底是如何工作的,但你应该在创建 Claimprinciple 时传递一个字符串参数“auth”,如下所示:
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
{
new Claim( ClaimTypes.Name, "newbie"),
new Claim( ClaimTypes.Role, "guest")
}, "auth"));
return await Task.FromResult(new AuthenticationState(claimsPrincipal));
}
字符串可以是任何东西。