【问题标题】:How to get the roles from a JWT token from a web api in Angular如何从 Angular 中的 Web api 的 JWT 令牌中获取角色
【发布时间】:2020-09-06 17:01:11
【问题描述】:

我需要从我的 JWT 令牌中获取角色,该令牌是使用声明在 asp.net 核心中创建的。这是我得到的令牌:

FirstName: "Juan"
LastName: "Dela Cruz"
MiddleName: "A."
UserId: "2"
aud: "http://192.168.1.6:13735"
exp: 1590001134
http://schemas.microsoft.com/ws/2008/06/identity/claims/role: Array(2)
0: "User"
1: "Administrator"
length: 2
__proto__: Array(0)
iss: "http://192.168.1.6:13735"
jti: "5732c019-0f91-4e32-8f8d-93da43547346"
sub: "juan"

我在我的 web api 中使用这个代码得到这个

var claims = new List<Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Sub, applicationUser.UserName),
                    new Claim("UserId", applicationUser.Id.ToString()),
                    new Claim("FirstName", applicationUser.FirstName.ToString()),
                    new Claim("MiddleName", applicationUser.MiddleName.ToString()),
                    new Claim("LastName", applicationUser.LastName.ToString()),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                };

                foreach(var role in roles)
                {
                    claims.Add(new Claim(ClaimTypes.Role, role.RoleName));
                }

                var validIssuer = configuration["WebToken:Issuer"];
                var validAudience = configuration["WebToken:Audience"];

                var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["AmsToken:TokenKey"]));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                var tokenOptions = new JwtSecurityToken(
                        issuer: "http://192.168.1.6:13735",
                        audience: "http://192.168.1.6:13735",
                        claims: claims,
                        expires: DateTime.Now.AddHours(8),
                        signingCredentials: signinCredentials
                    );
                var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
                return Ok(new { Token = tokenString });

在我的 Angular 应用程序中,我需要获取角色,以便相应地隐藏或显示按钮。但是,我不知道如何从生成的 Web 令牌中获取角色。这就是我从令牌中获取角色的方式:

 // Show or hide the navigation links
  roleMatch(): void {
    debugger;
    let isMatch = false;
    const payload = JSON.parse(window.atob(localStorage.getItem('authToken').split('.')[1]));
    const userRole = payload.role; ======> I get undefined on this part
  }

能否请您指出如何获得我需要的东西?谢谢。

【问题讨论】:

    标签: angular asp.net-core jwt


    【解决方案1】:

    要解码你需要一个库的令牌,我个人使用这个:https://github.com/auth0/angular2-jwt

    然后通过 npm 或其他数据包管理器安装它:

    $ npm install @auth0/angular-jwt
    

    您导入模块并实例化 JwtHelperService 类的实例:

    import { JwtHelperService } from "@auth0/angular-jwt";
    
    const helper = new JwtHelperService();
    

    然后你应该能够解码你的令牌:

    const decodedToken = helper.decodeToken(myRawToken);
    

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 2021-04-07
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 2018-01-13
      • 2021-04-10
      • 1970-01-01
      相关资源
      最近更新 更多