简体   繁体   English

如何在由 angular 和 .net 核心 web api 组成的全栈应用程序中管理用户角色和权限

[英]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我正在开发一个完整的堆栈 web 应用程序,在应用程序的客户端部分,我使用 angular 和 .net 核心 web api 作为应用程序的后端部分,我正在研究如何在用户登录时将用户角色从后端获取到客户端应用程序成功进入系统,因为我使用 jwt 身份验证,我能够获得 email 地址,如果用户存在于数据库中,我将其添加到声明身份中,如下所示

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并从客户端应用程序通过解码成功登录后从后端发送的令牌来获取此用户 email

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.因此,我不知道如何在声明身份中添加角色以及 email 添加并从 angular 应用程序中的令牌获取它们,在那里我可以将它们用作用户权限来访问客户端应用程序中的组件,在此先感谢您。

The easiest way is to add roles to your claims with a loop.最简单的方法是使用循环将角色添加到您的声明中。 This is a complete method for creating jwt tokens.这是创建 jwt 个令牌的完整方法。

    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);
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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