无法使用 ASP.NET Core 从 JWT 令牌获取声明

Can#39;t get claims from JWT token with ASP.NET Core(无法使用 ASP.NET Core 从 JWT 令牌获取声明)
本文介绍了无法使用 ASP.NET Core 从 JWT 令牌获取声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试使用 ASP.NET Core 实现一个非常简单的 JWT 不记名身份验证.我从控制器返回的响应有点像这样:

I'm trying to do a really simple implementation of JWT bearer authentication with ASP.NET Core. I return a response from a controller a bit like this:

    var identity = new ClaimsIdentity();
    identity.AddClaim(new Claim(ClaimTypes.Name, applicationUser.UserName));
        var jwt = new JwtSecurityToken(
             _jwtOptions.Issuer,
             _jwtOptions.Audience,
             identity.Claims,
             _jwtOptions.NotBefore,
             _jwtOptions.Expiration,
             _jwtOptions.SigningCredentials);

       var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

       return new JObject(
           new JProperty("access_token", encodedJwt),
           new JProperty("token_type", "bearer"),
           new JProperty("expires_in", (int)_jwtOptions.ValidFor.TotalSeconds),
           new JProperty(".issued", DateTimeOffset.UtcNow.ToString())
       );

我有用于传入请求的 Jwt 中间件:

I have Jwt middleware for incoming requests:

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
     AutomaticAuthenticate = true,
     AutomaticChallenge = true,
     TokenValidationParameters = tokenValidationParameters
});

这似乎可以使用 authorize 属性保护资源,但声明从未出现.

This seems to work to protect resources with the authorize attribute, but the claims never show up.

    [Authorize]
    public async Task<IActionResult> Get()
    {
        var user = ClaimsPrincipal.Current.Claims; // Nothing here

推荐答案

您不能在 ASP.NET Core 应用程序中使用 ClaimsPricipal.Current,因为它不是由运行时设置的.您可以阅读 https://github.com/aspnet/Security/issues/322 了解更多信息.

You can't use ClaimsPricipal.Current in an ASP.NET Core application, as it's not set by the runtime. You can read https://github.com/aspnet/Security/issues/322 for more information.

相反,请考虑使用 ControllerBase 公开的 User 属性.

Instead, consider using the User property, exposed by ControllerBase.

这篇关于无法使用 ASP.NET Core 从 JWT 令牌获取声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Custom Error Queue Name when using EasyNetQ for RabbitMQ?(使用 EasyNetQ for RabbitMQ 时自定义错误队列名称?)
How to generate password_hash for RabbitMQ Management HTTP API(如何为 RabbitMQ 管理 HTTP API 生成密码哈希)
Rabbitmq Ack or Nack, leaving messages on the queue(Rabbitmq Ack 或 Nack,将消息留在队列中)
Setup RabbitMQ consumer in ASP.NET Core application(在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者)
Specify Publish timeouts in mass transit(指定公共交通中的发布超时)
RabbitMQ asynchronous support(RabbitMQ 异步支持)