[英]How to customize the login page of ASP.NET Core web application with Angular Individual user account authentication?
[英]how to manage user roles and permission in a full stack application made up of angular and .net core web api
我正在开发一个完整的堆栈 web 应用程序,在应用程序的客户端部分,我使用 angular 和 .net 核心 web api 作为应用程序的后端部分,我正在研究如何在用户登录时将用户角色从后端获取到客户端应用程序成功进入系统,因为我使用 jwt 身份验证,我能够获得 email 地址,如果用户存在于数据库中,我将其添加到声明身份中,如下所示
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Email, obj.Email)
})
并从客户端应用程序通过解码成功登录后从后端发送的令牌来获取此用户 email
In Typescript File
var tokenData = jwtHelper.decodeToken(token);
In HTML form
{{ tokenData.email }}
因此,我不知道如何在声明身份中添加角色以及 email 添加并从 angular 应用程序中的令牌获取它们,在那里我可以将它们用作用户权限来访问客户端应用程序中的组件,在此先感谢您。
最简单的方法是使用循环将角色添加到您的声明中。 这是创建 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.