如何解码JWT Token?

Coo*_*kie 72 .net c# jwt

我不明白这个库是如何工作的.请问你能帮帮我吗 ?

这是我的简单代码:

public void TestJwtSecurityTokenHandler()
    {
        var stream =
            "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJJU1MiLCJzY29wZSI6Imh0dHBzOi8vbGFyaW0uZG5zY2UuZG91YW5lL2NpZWxzZXJ2aWNlL3dzIiwiYXVkIjoiaHR0cHM6Ly9kb3VhbmUuZmluYW5jZXMuZ291di5mci9vYXV0aDIvdjEiLCJpYXQiOiJcL0RhdGUoMTQ2ODM2MjU5Mzc4NClcLyJ9";
        var handler = new JwtSecurityTokenHandler();

        var jsonToken = handler.ReadToken(stream);
    }
Run Code Online (Sandbox Code Playgroud)

这是错误:

字符串需要采用紧凑的JSON格式,格式如下:Base64UrlEncodedHeader.Base64UrlEndcodedPayload.OPTIONAL,Base64UrlEncodedSignature'.

如果你在jwt.io网站上复制流,它工作正常:)

Coo*_*kie 111

我找到了解决方案,我只是错过了Cast结果如下:

var stream ="[encoded jwt]";  
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(stream);
var tokenS = handler.ReadToken(stream) as JwtSecurityToken;
Run Code Online (Sandbox Code Playgroud)

在我得到索赔之后:

var jti = tokenS.Claims.First(claim => claim.Type == "jti").Value;
Run Code Online (Sandbox Code Playgroud)

  • 抱歉,这应该很明显,但是tokenJwtReponse.access_token来自何处? (13认同)
  • 你也可以这样做:handler.ReadJwtToken(tokenJwtReponse.access_token); (8认同)
  • 正如其他人已经质疑的那样:“ tokenJwtReponse.access_token”来自何处?答案中没有定义或声明,这使答案对于我们许多人来说毫无用处和意义。 (4认同)
  • tokenJwtReponse.access_token来自哪里? (3认同)
  • 我需要包含以下 NuGet 包才能在我的 Azure 函数中使用它:System.IdentityModel.Tokens.Jwt (3认同)
  • 我必须首先将tokenS.Claims转换为声明列表.`((List <Claim>)tokenS.Claims).ForEach(a => Console.WriteLine(a.Type.ToString()+""+ a.Value));` (2认同)

dpi*_*pix 19

new JwtSecurityTokenHandler().ReadToken("") 会回来的 SecurityToken

new JwtSecurityTokenHandler().ReadJwtToken("") 会回来的 JwtSecurityToken

如果您只是更改正在使用的方法,则可以避免上述答案中的演员表


小智 15

我写了这个解决方案,它对我有用

    protected Dictionary<string, string> GetTokenInfo(string token)
    {
        var TokenInfo = new Dictionary<string, string>();

        var handler = new JwtSecurityTokenHandler();
        var jwtSecurityToken = handler.ReadJwtToken(token);
        var claims = jwtSecurityToken.Claims.ToList();

        foreach (var claim in claims)
        {
            TokenInfo.Add(claim.Type, claim.Value);
        }

        return TokenInfo;
    }
Run Code Online (Sandbox Code Playgroud)


jen*_*ent 14

使用 .net core jwt 包,Claim 可用:

[Route("api/[controller]")]
[ApiController]
[Authorize(Policy = "Bearer")]
public class AbstractController: ControllerBase
{
    protected string UserId()
    {
        var principal = HttpContext.User;
        if (principal?.Claims != null)
        {
            foreach (var claim in principal.Claims)
            {
               log.Debug($"CLAIM TYPE: {claim.Type}; CLAIM VALUE: {claim.Value}");
            }

        }
        return principal?.Claims?.SingleOrDefault(p => p.Type == "username")?.Value;
    }
}
Run Code Online (Sandbox Code Playgroud)


Jin*_*esh 12

  var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
  var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
  var claims = new[]
  {
      new Claim(JwtRegisteredClaimNames.Email, model.UserName),
      new Claim(JwtRegisteredClaimNames.NameId, model.Id.ToString()),
  };
  var token = new JwtSecurityToken(_config["Jwt:Issuer"],
      _config["Jwt:Issuer"],
      claims,
      expires: DateTime.Now.AddMinutes(30),
      signingCredentials: creds);
Run Code Online (Sandbox Code Playgroud)

然后提取内容

 var handler = new JwtSecurityTokenHandler();
 string authHeader = Request.Headers["Authorization"];
 authHeader = authHeader.Replace("Bearer ", "");
 var jsonToken = handler.ReadToken(authHeader);
 var tokenS = handler.ReadToken(authHeader) as JwtSecurityToken;
 var id = tokenS.Claims.First(claim => claim.Type == "nameid").Value;
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,如果您不喜欢硬编码字符串,可以将“Authorization”更改为“Microsoft.Net.Http.Headers.HeaderNames.Authorization” (2认同)

小智 9

您需要使用用于生成加密令牌的秘密字符串。该代码对我有用:

protected string GetName(string token)
    {
        string secret = "this is a string used for encrypt and decrypt token"; 
        var key = Encoding.ASCII.GetBytes(secret);
        var handler = new JwtSecurityTokenHandler();
        var validations = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
        var claims = handler.ValidateToken(token, validations, out var tokenSecure);
        return claims.Identity.Name;
    }
Run Code Online (Sandbox Code Playgroud)