[英]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.