Visual Studio 如何解码JWT令牌?

km0tfn4u  于 2022-12-19  发布在  其他
关注(0)|答案(9)|浏览(192)

我不明白这个图书馆是怎么运作的,你能帮我一下吗?
下面是我的简单代码:

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

        var jsonToken = handler.ReadToken(stream);
    }

这是错误:
字符串需要采用紧凑的JSON格式,格式如下:“Base64UrlEncodedHeader.Base64UrlEndcodedPayload.可选,Base64UrlEncodedSignature”。
如果你在www.example.com网站上复制流jwt.io,它工作得很好:)

8wigbo56

8wigbo561#

我找到了解决方案,只是忘了转换结果:

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

或者,如果没有石膏:

var token = "[encoded jwt]";  
var handler = new JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(token);

我可以使用以下方法获取报销申请:

var jti = tokenS.Claims.First(claim => claim.Type == "jti").Value;
xoefb8l8

xoefb8l82#

new JwtSecurityTokenHandler().ReadToken("")将返回一个
new JwtSecurityTokenHandler().ReadJwtToken("")将返回一个
如果你只是改变你正在使用的方法,你可以避免以上答案中的强制转换

snvhrwxg

snvhrwxg3#

您需要用来生成加密令牌的秘密字符串。以下代码对我有效:

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;
    }
3vpjnl9f

3vpjnl9f4#

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

然后提取内容

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

klsxnrf15#

使用.net core jwt软件包,可获得以下声明:

[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;
    }
}
9o685dep

9o685dep6#

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

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;
    }
lzfw57am

lzfw57am7#

扩展cooxkie应答和dpix应答,当你阅读jwt令牌(如从AD FS接收的access_token)时,你可以将jwt令牌中的声明与“context.AuthenticationTicket.Identity”中的声明合并,这些声明可能与jwt令牌具有不同的声明集。
举例来说,在使用OpenID Connect的验证代码流程中,用户通过验证后,您可以处理事件SecurityTokenValidated,它为您提供了验证上下文,然后您可以使用它将access_token作为jwt令牌读取,然后您可以将access_token中的令牌与作为用户身份的一部分接收的声明的标准列表“合并”:

private Task OnSecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage,OpenIdConnectAuthenticationOptions> context)
    {
        //get the current user identity
        ClaimsIdentity claimsIdentity = (ClaimsIdentity)context.AuthenticationTicket.Identity;

        /*read access token from the current context*/
        string access_token = context.ProtocolMessage.AccessToken;

        JwtSecurityTokenHandler hand = new JwtSecurityTokenHandler();
        //read the token as recommended by Coxkie and dpix
        var tokenS = hand.ReadJwtToken(access_token);
        //here, you read the claims from the access token which might have 
        //additional claims needed by your application
        foreach (var claim in tokenS.Claims)
        {
            if (!claimsIdentity.HasClaim(claim.Type, claim.Value))
                claimsIdentity.AddClaim(claim);
        }

        return Task.FromResult(0);
    }
xzv2uavs

xzv2uavs8#

请使用此选项:

public static string Get_Payload_JWTToken(string token)
    {
        var handler = new JwtSecurityTokenHandler();
        var DecodedJWT = handler.ReadJwtToken(token);
        string payload = DecodedJWT.EncodedPayload;  // Gives Payload
        return Encoding.UTF8.GetString(FromBase64Url(payload));
    }
    static byte[] FromBase64Url(string base64Url)
    {
        string padded = base64Url.Length % 4 == 0
        ? base64Url : base64Url + "====".Substring(base64Url.Length % 4);
        string base64 = padded.Replace("_", "/").Replace("-", "+");
        return Convert.FromBase64String(base64);
    }
ztigrdn8

ztigrdn89#

虽然这个答案没有回答最初的问题,但它对C#开发人员来说确实是一个非常有用的特性,所以添加它作为答案。
Visual Studio 2022添加了在运行时解码标记值的功能。
您可以在Visual Studio 2022预览版(版本17.5.0预览版2.0)中检查该功能
将鼠标移到包含JWT的变量上,然后选择字符串操作作为JWTDecode,您可以看到标记值。

相关问题