简体   繁体   中英

how to manage user roles and permission in a full stack application made up of angular and .net core web api

Am developing a full stack web application where in client part of the app am using angular and .net core web api as the backend part of the application, am stack on how i can get the user roles from the backend into the client app when user login successfully into the system since am using jwt authentication, am able to get the email address which i added it in claims identity if user exists in the database as below

var tokenDescriptor = new SecurityTokenDescriptor
               {
                    Subject = new ClaimsIdentity(new Claim[]
                {
                new Claim(ClaimTypes.Email, obj.Email)
                })  

and from client application am getting this user email by decoding the token sent from backend after successfully login as

In Typescript File
    var tokenData = jwtHelper.decodeToken(token);
In HTML form
    {{ tokenData.email }}

Therefore, i don't know how i can add roles in claims identity together with email added and obtain them from token in angular app where i can use them as user permissions to access components in client application, thank you in advance.

The easiest way is to add roles to your claims with a loop. This is a complete method for creating jwt tokens.

    public string GenarateToken(User user)
    {
        var claims =new List<Claim>()
        {
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
            new Claim(ClaimTypes.Name, user.UserName),
        };

        foreach (var role in user.Roles)
        {
            claims.Add(new Claim(ClaimTypes.Role, role.Name));
        }
       
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_conf.GetSection("AppSettings:secret").Value));

        var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(claims),
            Expires = DateTime.Now.AddDays(1),
            SigningCredentials = cred
        };

        var tokenHandler = new JwtSecurityTokenHandler();

        var token = tokenHandler.CreateToken(tokenDescriptor);

        return tokenHandler.WriteToken(token);
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM