如何在 angular 应用程序中使用它从 JWT 令牌获取角色名称?

How to get the role name from JWT Token using it in angular app?

这是我的登录方法,我从中生成 JWT 令牌,然后将其存储在浏览器的 localStorage 中:

[HttpPost]
    [Route("Login")]
    public async Task<IActionResult> Login([FromBody] LoginModel model)
    {
        //var userID_Name = _context.Users.Where(a => a.UserName == model.UserName).ToList();
        var user = await userManager.FindByNameAsync(model.UserName);
        var userlogintime = 1;
        if (model.RememberMe == true) 
        {
            userlogintime = 7;
        }
        if (user != null && await userManager.CheckPasswordAsync(user, model.Password)) 
        {
            if (!await userManager.IsEmailConfirmedAsync(user))
            {
                return Ok(new Response { Status = "Error", Message = "Please Activate your Account by Confirming your Email!" });
            }
            else
            {
                var userRoles = await userManager.GetRolesAsync(user);
                var authClaims = new List<Claim>
            {
                new Claim("UserId",user.Id),
                new Claim("Username",user.UserFullName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };
                foreach (var userRole in userRoles)
                {
                    authClaims.Add(new Claim(ClaimTypes.Role, userRole));
                }
                var authSigninKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));
                var token = new JwtSecurityToken(
                    issuer: _configuration["JWT:ValidIssuer"],
                    audience: _configuration["JWT:ValidAudience"],
                    expires: DateTime.Now.AddDays(userlogintime),
                    claims: authClaims,
                    signingCredentials: new SigningCredentials(authSigninKey, SecurityAlgorithms.HmacSha256Signature)
                    );
                return Ok(new Response
                {
                    //Status = userID_Name[0].Id.ToString() + ";" + userID_Name[0].UserFullName.ToString(),
                    Message = "Login Successfull!",
                    Token = new JwtSecurityTokenHandler().WriteToken(token)
                });
            }                
        }
        return Ok(new Response { Status="Error", Message= "Invalid Email or Password!" });
    }

现在,当我解码令牌时,我得到的解码令牌如下:

UserId: "03e57d11-2981-4f8c-997e-ac8d6a5ee1e6"
Username: "Farooq Butt"
aud: "User"
exp: 1613021989
http://schemas.microsoft.com/ws/2008/06/identity/claims/role: "Administrator"
iss: "http://localhost:59286"
jti: "afc4a466-7970-458d-8c59-520a45255a73"

现在我想在我的 angular 应用程序中获取此管理员名称,但我正在使用

JSON.parse(window.atob(localStorage.getItem('userToken').split('.')[1])).Username

它很好用,但是当我使用它时

JSON.parse(window.atob(localStorage.getItem('userToken').split('.')[1])).http://schemas.microsoft.com/ws/2008/06/identity/claims/role

会return错误。

试试这个

JSON.parse(window.atob(localStorage.getItem('userToken').split('.')[1]))["http://schemas.microsoft.com/ws/2008/06/identity/claims/role"]

如何访问属性:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors