直接从令牌ASP Net Core 2.1获取JWT声明 [英] Get JWT claims directly from the token, ASP Net Core 2.1

查看:77
本文介绍了直接从令牌ASP Net Core 2.1获取JWT声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究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 类继承的控制器中,所以我没有任何 User 对象或 [Authorize] 属性.

我所拥有的只是令牌本身.
例如

<预> <代码> eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwiZW1haWwiOiJhZG1pbiIsIm5iZiI6MTU2ODYzNjYxMywiZXhwIjoxNTY4NjQ3NDEzLCJpYXQiOjE1Njg2MzY2MTN9.ED9x_AOvkLQqutb09yh3Huyv0ygHp_i3Eli8WG2S9N4

我想直接从令牌中获得索赔,因为:

  1. 我可以使用令牌.
  2. 我不在Controller类中,并且请求没有通过任何 [Authorize] 属性,因此也无法使用 IHttpContextAccessor .
  3. li>

如何在ASP Net Core 2.1中实现此目标?如果有人想看看我如何添加用户声明:

  var tokenDescriptor = new SecurityTokenDescriptor{过期= DateTime.UtcNow.AddHours(3),主题=新的ClaimsIdentity(new []{新的Claim(ClaimTypes.Name,email),新的Claim(ClaimTypes.Email,email)}),SigningCredentials =新的SigningCredentials(密钥:新的SymmetricSecurityKey(密钥),算法:SecurityAlgorithms.HmacSha256Signature)};var token = tokenHandler.CreateToken(tokenDescriptor); 

我位于从 IDocumentFilter (Swagger类)

派生的类中

解决方案

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

  var tokenDescriptor =新的SecurityTokenDescriptor{过期= DateTime.UtcNow.AddHours(3),主题=新的ClaimsIdentity(new []{新的Claim(ClaimTypes.Name,"user@hotmail.com"),新的Claim(ClaimTypes.Email,"user@hotmail.com")}),SigningCredentials =新的SigningCredentials(密钥:新的SymmetricSecurityKey(密钥),算法: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;退还索赔; 

I working on an ASP Net Core 2.1 Web API. I've implemented successfully JWT within my project. Everything with the Authorization works fine.

Normally, when I need user claims, I know I can get them like this (E.g. Email claim):

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

The thing is, I am not in a controller that inherits from ControllerBase class, so I don't have any User object or [Authorize] attributes.

What I have though is the token itself.
e.g.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwiZW1haWwiOiJhZG1pbiIsIm5iZiI6MTU2ODYzNjYxMywiZXhwIjoxNTY4NjQ3NDEzLCJpYXQiOjE1Njg2MzY2MTN9.ED9x_AOvkLQqutb09yh3Huyv0ygHp_i3Eli8WG2S9N4

I want to get the claims directly from the token, because:

  1. I have access to the token.
  2. I am not located in a Controller class and the request is not going through any [Authorize] attributes, so IHttpContextAccessor can't be used as well.

How can I achieve this in ASP Net Core 2.1? In case someone wants to see how I add the user claims:

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);

I'm located in a class that derives from IDocumentFilter (Swagger class)

解决方案

Here is a simple workaround:

    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;

这篇关于直接从令牌ASP Net Core 2.1获取JWT声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆