C'est ma méthode de connexion à partir de laquelle je génère le jeton JWT, puis je le stocke dans le stockage local de mon navigateur:

[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!" });
    }

Maintenant, lorsque je décodais le jeton, je reçois le jeton décodé comme ci-dessous:

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"

Maintenant, je veux obtenir ce nom d'administrateur dans mon application angulaire mais j'utilise

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

Ça marche bien mais quand j'utilise ça

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

Il renverra une erreur.

0
Farooq Butt 4 févr. 2021 à 10:01

1 réponse

Meilleure réponse

Essaye ça

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

Comment accéder aux propriétés: https: //developer.mozilla .org / en-US / docs / Web / JavaScript / Reference / Operators / Property_accessors

1
Stanislav Berkov 4 févr. 2021 à 07:11