简体   繁体   English

直接从令牌中获取 JWT 声明,ASP Net Core 2.1

[英]Get JWT claims directly from the token, ASP Net Core 2.1

I working on an ASP Net Core 2.1 Web API.我正在研究 ASP Net Core 2.1 Web API。 I've implemented successfully JWT within my project.我已经在我的项目中成功实现了 JWT。 Everything with the Authorization works fine.具有授权的一切工作正常。

Normally, when I need user claims, I know I can get them like this (Eg 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.问题是,我不在从ControllerBase类继承的ControllerBase ,所以我没有任何User对象或[Authorize]属性。

What I have though is the token itself.我所拥有的是令牌本身。
eg例如

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.我不在 Controller 类中,并且请求没有通过任何[Authorize]属性,因此也不能使用IHttpContextAccessor

How can I achieve this in ASP Net Core 2.1?如何在 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)我位于从IDocumentFilter派生的类中(Swagger 类)

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;

For example in my current project I get claims by validation.例如,在我当前的项目中,我通过验证获得了声明。 Its refresh token, so I cant use [Authorize] attribute.它的刷新令牌,所以我不能使用 [Authorize] 属性。

using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

public ClaimsPrincipal ValidateRefreshToken(string refreshToken)
{
    try
    {
        var validationParams = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(tokenSecurityKey),
            ValidateLifetime = true
        };
        return new JwtSecurityTokenHandler().ValidateToken
        (
            refreshToken, 
            validationParams, 
            out SecurityToken token
        );
    }
    catch (Exception e)
    {
        Log.Error(e.Message);
        return null;
    }
}

and then进而

var claims = ValidateRefreshToken(refreshToken);
...
var userIdString = claims.Claims.FirstOrDefault(x => x.Type == "userId")?.Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM