【问题标题】:Decrypting Jwt token in JavaScript在 JavaScript 中解密 Jwt 令牌
【发布时间】:2020-06-23 15:38:26
【问题描述】:

我正在加密这样的令牌:

var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_configuration.GetSection("TokenAuthentication:SecretKey").Value));
var encryptingCredentials = new EncryptingCredentials(signingKey, JwtConstants.DirectKeyUseAlg, SecurityAlgorithms.Aes256CbcHmacSha512);
            
// Create the JWT and write it to a string
var jwtSecurityToken = new JwtSecurityTokenHandler().CreateJwtSecurityToken(
    issuer: _configuration.GetSection("TokenAuthentication:Issuer").Value,
    audience: _configuration.GetSection("TokenAuthentication:Audience").Value,
    subject: new ClaimsIdentity(claims),
    notBefore: now,
    expires: now.Add(TimeSpan.FromMinutes(5)),
    now,
    signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
    encryptingCredentials: encryptingCredentials
);

var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

在 dotnet 核心服务中,我希望能够在 JavaScript 中解密令牌。我已经尝试了来自“Decrypting signature and Veryifying JWT”的解决方案,但无法比“错误:格式错误的 UTF-8 数据”更进一步。

有简单的解决办法吗?

【问题讨论】:

  • 有什么理由像链接的 q/a 中那样手动进行吗?通常我会建议使用众多JWT libraries 之一。顺便提一句。要获取 JWT 的有效负载数据,您只需 decode JWT,因为它只是 base64url encodednot encrypted
  • 或许你可以试试这个功能stackoverflow.com/questions/38552003/…
  • 为什么要“解密”JWT?你期望从中得到什么,为什么? JWT 应该被视为传递给服务器的令牌。除了通过 HTTP 请求传递它们之外,客户端与它们没有任何关系?
  • @Liam 这是真的。尤其是。当您使用对称密钥时(如问题中所示),在客户端共享密钥是一个很大的禁忌!
  • 好的,所以可能会丢失加密?我想解码密钥以获取声明、用户名等。

标签: javascript .net-core jwt


【解决方案1】:

您可以使用许多库来实现此目的。 njwt 就是其中之一。

了解 JWT 机制的工作原理很重要。涵盖一些理论,这将节省大量调试时间。

但是,无论您使用什么库,您都必须在生产设置中密切注意以下事项:

  1. 正确安全地存储私钥
  2. 使用密钥解析器安全地加载私钥

这是开始这一切的一种方式:

首先,从硬编码方法开始。一旦您知道您的令牌验证有效,请计划安全地存储您的密钥并使用基于 kid 标准声明的密钥解析器(上述库的一部分)加载它。

这是没有上述任何标准做法的核心令牌验证。

nJwt.verify(token,signingKey,function(err,verifiedJwt){
  if(err){
    console.log(err); // Token has expired, has been tampered with, etc
  }else{
    console.log(verifiedJwt); // Will contain the header and body
  }
});

【讨论】:

    【解决方案2】:

    尝试使用这个https://github.com/auth0/jwt-decode。 你不需要在那里做棘手的事情。只需将带有 JWT 令牌的字符串作为“jwt_decode”函数的参数即可。

    【讨论】:

      猜你喜欢
      • 2017-03-07
      • 1970-01-01
      • 2020-09-13
      • 2019-07-25
      • 2018-11-25
      • 2021-03-07
      • 2015-01-02
      • 2023-01-14
      • 1970-01-01
      相关资源
      最近更新 更多