【问题标题】:@auth0/angular-jwt : Get claims from decoded token@auth0/angular-jwt : 从解码的令牌中获取声明
【发布时间】:2021-04-21 07:56:04
【问题描述】:

?我通过“@auth0/angular-jwt”获得了我的 Angular 10 应用程序 JWT 令牌。在解码函数后,我得到一个声明列表,如下所示:

{
  http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: "johndoe", 
  http://schemas.microsoft.com/ws/2008/06/identity/claims/role: "Manager", 
  exp: 1525510870, 
  iss: "http://localhost:5000", 
  aud: "http://localhost:5000"
}

我如何通过 typescript 获得自定义声明,例如:

{
  name: "johndoe", 
  role: "Manager", 
}

? 谢谢。

【问题讨论】:

    标签: angular decode auth0 jwt-auth claims


    【解决方案1】:

    我找到了解决办法:

    const token = {
      'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': "johndoe", 
      'http://schemas.microsoft.com/ws/2008/06/identity/claims/role': "Manager", 
      'exp': 1525510870, 
      'iss': "http://localhost:5000", 
      'aud': "http://localhost:5000"
    }
    
    const decodedName = token['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name']
    const decodedRole = token['http://schemas.microsoft.com/ws/2008/06/identity/claims/role']
    console.log(decodedName)
    console.log(decodedRole)
    

    【讨论】:

      【解决方案2】:

      如果 JWT 由 3 部分组成,则您必须对其中的部分进行解码 从中间开始,即包含声明的主体,第一个 是一个标头,最后一个 - JWT Signature。

      因此,有了一个令牌,我们想要获取它的声明,所以我们从中间解码部分并将其解析为 json,这样我们就可以将声明作为该对象的字段来访问。

      let token = localStorage.getItem('token');
      let decodedJWT = JSON.parse(window.atob(token.split('.')[1]));
      
      console.log('name: ' + decodedJWT.name);
      console.log('role: ' + decodedJWT.role);
      

      【讨论】:

        猜你喜欢
        • 2021-10-20
        • 1970-01-01
        • 2018-01-13
        • 2018-06-16
        • 2021-04-23
        • 2017-02-13
        • 2020-07-30
        • 2020-01-17
        • 2023-03-23
        相关资源
        最近更新 更多