【问题标题】:Asp.Net Core role system without Identity没有身份的 Asp.Net Core 角色系统
【发布时间】:2020-11-05 14:57:02
【问题描述】:

如何添加没有身份的角色系统?我需要成员和管理员角色。

登录代码:

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

Startup.cs

 services.AddAuthorization(opt =>
    {
        opt.AddPolicy("Admin", policy => policy.RequireClaim(ClaimTypes.Name));
    });

【问题讨论】:

    标签: c# asp.net-core roles


    【解决方案1】:

    如何添加没有身份的角色系统?我需要成员和管理员角色。

    据我所知,如果你使用了asp.net core cookie认证,是不需要搭建角色系统的。

    我们可以在您的登录逻辑中编写代码来检查数据库中的用户角色。

    然后我们可以通过添加 ClaimTypes.Role 声明来添加角色。然后我们可以使用 [Authorize(Roles ="Admin")]属性让只有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);
    

    在控制器上:

    [Authorize(Roles ="Admin")]
    public class AdminController : Controller
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 2018-09-06
      • 2016-09-05
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      • 2017-12-22
      相关资源
      最近更新 更多