在Blazor WASM AspNetCore Hosted应用程序中使用JWT进行身份验证时,可能会出现以下问题: 在进行身份验证时,JWT令牌没有正确传递到API端点,并且API端点始终返回未经授权的错误。
解决此问题的方法是配置应用程序程序集中的AuthorizationOptions。在Startup.cs文件中的ConfigureServices()方法中,添加以下代码:
services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.Authority = "https://yourauthority.com"; options.Audience = "your-audience"; });
其中,options.Authority是认证服务的地址,而options.Audience是你的应用程序的身份验证程序。
然后,在启用端点身份验证的中间件之前,为应用程序指定身份验证策略。
添加以下策略定义:
services.AddAuthorization(options => { options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser() .Build(); });
最后,确保在应用程序的所有API控制器上使用身份验证特性[Authorize]进行身份验证。
示例代码如下:
[Authorize] [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { //... }
完成上述步骤后,应用程序将正确传递JWT令牌,并允许通过API端点进行身份验证。
上一篇:BlazorWASMASP.NETCorehostedwithIdentitydoesn'tworkwhendeployed
下一篇:BlazorWASMAuthenticationStateusingAAD-ClaimsnulluntilRefresh