[英]Asp.Net Core role system without Identity
如何添加没有身份的角色系统? 我需要成员和管理员角色。
登录代码:
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, loginDTO.StrUserID)
};
var userIdentity = new ClaimsIdentity(claims, "login");
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync(principal);
启动.cs
services.AddAuthorization(opt =>
{
opt.AddPolicy("Admin", policy => policy.RequireClaim(ClaimTypes.Name));
});
如何添加没有身份的角色系统? 我需要成员和管理员角色。
据我所知,如果你使用asp.net核心cookie认证,是不需要搭建角色系统的。
我们可以在您的登录逻辑中编写代码来检查数据库中的用户角色。
然后我们可以通过添加 ClaimTypes.Role Claim 来添加角色。 然后我们可以使用[Authorize(Roles ="Admin")]
属性让只有管理员角色的用户访问。
更多细节,您可以参考以下代码:
//Here build the logic to get the user role from database, then create a new role claim to add the user role.
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "TestA"),
new Claim(ClaimTypes.Role, "Admin"),
};
var userIdentity = new ClaimsIdentity(claims, "login");
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
HttpContext.SignInAsync(principal);
在 controller 上:
[Authorize(Roles ="Admin")]
public class AdminController : Controller
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.