【发布时间】:2022-02-14 18:49:33
【问题描述】:
我在后端使用 ASP.NET Core Web API,并在 Blazor WASM 客户端的 httpClient 标头中使用 JWT 令牌(我不将 JWT 令牌存储在 cookie 中)。
问题在于,虽然用户已经登录并且身份验证和授权工作没有问题,但在每个控制器中(继承自ControllerBase)总是:
-
HttpContext.User.Identity.IsAuthenticated是假的 -
HttpContext.User.Identity.Name为空 -
HttpContext.User.Claims为空
但请求具有 JWT 令牌(Request.Headers["Authorization"][0] 等于 Bearer eyJhbGciOiJIUzI1...)并且 [Authorize] 属性正常工作。
这就是我的 startup.cs 的样子:
services.AddIdentity()
services.AddSingleton<IAuthorizationPolicyProvider, AuthorizeExPolicyProvider>();
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
});
services.AddAuthorization(options =>
{
});
我还以正确的顺序调用了中间件:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
【问题讨论】:
-
您能告诉我们您添加到控制器的属性吗?
-
@Nisd 在这种情况下仅使用 HttpGet。但是还有其他具有 Authorize 属性的方法
-
@Nisd 您的评论很有帮助。实际上,我正在使用没有任何 Authorize 属性的方法对其进行测试,因此答案是使用 Authorize Attribute 。随意添加它作为答案。谢谢
标签: c# jwt asp.net-core-webapi asp.net-core-identity