c# - 直接从token获取JWT声明,ASP Net Core 2.1

标签 c# asp.net-core jwt asp.net-core-webapi

我正在研究 ASP Net Core 2.1 Web API。我已经在我的项目中成功实现了 JWT。获得授权的一切都可以正常工作。

通常,当我需要用户声明时,我知道我可以像这样获得它们(例如电子邮件声明):

var claimsIdentity = User.Identity as ClaimsIdentity;
var emailClaim = claimsIdentity.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Email);

问题是,我不在继承自 ControllerBase 类的 Controller 中,所以我没有任何 User 对象或 [Authorize] 属性。

不过我拥有的是 token 本身。
例如

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwiZW1haWwiOiJhZG1pbiIsIm5iZiI6MTU2ODYzNjYxMywiZXhwIjoxNTY4NjQ3NDEzLCJpYXQiOjE1Njg2MzY2MTN9.ED9x_AOvkLQqutb09yh3Huyv0ygHp_i3Eli8WG2S9N4

我想直接从 token 中获取声明,因为:

  1. 我可以访问 token 。
  2. 我不在 Controller 类中并且请求没有通过任何 [Authorize] 属性,因此也不能使用 IHttpContextAccessor。<

如何在 ASP Net Core 2.1 中实现这一点?如果有人想看看我是如何添加用户声明的:

var tokenDescriptor = new SecurityTokenDescriptor
{
    Expires = DateTime.UtcNow.AddHours(3),
    Subject = new ClaimsIdentity(new[]
    {
        new Claim(ClaimTypes.Name, email),
        new Claim(ClaimTypes.Email, email)
    }),
    SigningCredentials = new SigningCredentials(key: new SymmetricSecurityKey(key), algorithm: SecurityAlgorithms.HmacSha256Signature)
};

var token = tokenHandler.CreateToken(tokenDescriptor);

我位于派生自 IDocumentFilter(Swagger 类)的类中

最佳答案

这是一个简单的解决方法:

    var tokenDescriptor = new SecurityTokenDescriptor
        {
            Expires = DateTime.UtcNow.AddHours(3),
            Subject = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, "user@hotmail.com"),
                new Claim(ClaimTypes.Email, "user@hotmail.com")
            }),
            SigningCredentials = new SigningCredentials(key: new SymmetricSecurityKey(key), algorithm: SecurityAlgorithms.HmacSha256Signature)
        };

    var Securitytoken = new JwtSecurityTokenHandler().CreateToken(tokenDescriptor);
    var tokenstring = new JwtSecurityTokenHandler().WriteToken(Securitytoken);
    var token = new JwtSecurityTokenHandler().ReadJwtToken(tokenstring);
    var claim = token.Claims.First(c => c.Type == "email").Value;
    return claim;

关于c# - 直接从token获取JWT声明,ASP Net Core 2.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57959822/

相关文章:

C#静态方法重构

c# - 输入字符串的格式不正确

asp.net-core - 如何以编程方式重新启动 asp.net 核心应用程序?

java - 从哪里获取用于在 Java 或 Kotlin 中验证 JWT token 的公钥

java - 在没有 OAuth 的情况下使用 JWT 安全吗?

c# - 将两个不同属性绑定(bind)在一起的简单方法?

c# - 有没有办法计算忽略初始化时间的测试方法的运行时间?

amazon-web-services - .net 核心中的 KeyedHashAlgorithm

c# - Asp.Net Core v1.1 从同一解决方案中的另一个项目获取继承的类名

c# - Asp.Net Core 3 Identity - 来自浏览器的 JWT 中不存在自定义声明