Asp.net core mvc ASP.NET核心自定义用户角色实现

Asp.net core mvc ASP.NET核心自定义用户角色实现,asp.net-core-mvc,roles,asp.net-authorization,Asp.net Core Mvc,Roles,Asp.net Authorization,我正在尝试定义用户角色的自定义方式,因为我的数据库的用户表结构如下: 角色是一个bool,因此如果用户是管理员,那么他就是一个普通用户 我知道我需要在Startup.cs.中声明add.UseAuthorization(),我可以添加属性[Roles=“Administrator”]/[Roles=“User”]在控制器内部但我不确定如何定义要由用户表中的角色列确定的角色 我一直在互联网上搜索,也在阅读有关政策的文章,但我认为这不是正确的实施方式。我在网上找到的所有东西都是关于某种身份结构

我正在尝试定义用户角色的自定义方式,因为我的数据库的用户表结构如下:


角色是一个bool,因此如果用户是管理员,那么他就是一个普通用户


我知道我需要在Startup.cs.中声明
add.UseAuthorization()
,我可以添加属性
[Roles=“Administrator”]
/
[Roles=“User”]
控制器内部但我不确定如何定义要由用户表中的角色列确定的角色

我一直在互联网上搜索,也在阅读有关政策的文章,但我认为这不是正确的实施方式。我在网上找到的所有东西都是关于某种身份结构的,但对于如何将其附加到我的角色栏中却毫无意义


希望有人能帮我。谢谢

如果您可以自由操作数据库,我强烈建议使用,它是一个强大的框架,可以集成到您自己的数据库中

但要具体回答您的问题,缺少两个步骤:

  • 选择用于登录用户的身份验证方案(例如,基于Cookie的…)
  • 用户登录后,将设计的角色保存在ClaimsPrincipal对象中。通过这种方式,
    [Authorize(Roles=“User”)]
    声明可以获取此信息
下面是一个在Visual Studio中使用默认ASP.NET核心模板的基本示例

  • 将身份验证中间件添加到您的
    ConfigureServices
    方法中,并使用
    AuthenticationScheme
    对其进行配置。在本例中,我使用Cookie身份验证

    //in ConfigureServices, add both middlewares
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie();
    
    //in the Configure() method, enable these middlewares
    app.UseAuthentication();
    app.UseCookiePolicy(new CookiePolicyOptions());
    
  • 现在你准备好行动了。假设您有一个Action方法,您希望在其中对用户进行身份验证。这是您想要转换角色的地方,以便
    [Authorize]

  • 从数据库中获取所需的值。你会得到一个
    bool
    。将其转换为角色
    索赔
    ,并将其添加到
    索赔实体

    bool roleFromDb = true;  //this comes from db
    
    //convert to Claim of "Role" type, and create a ClaimsIdentity with it
    var adminClaim = new Claim(ClaimTypes.Role, roleFromDb ? "Administrator" : "User"); 
    var claimIdentity = new ClaimsIdentity(new[] { adminClaim }, 
                        CookieAuthenticationDefaults.AuthenticationScheme);
    
    //signs in the user and add the ClaimsIdentity which states that user is Admin
    await HttpContext.SignInAsync(
            CookieAuthenticationDefaults.AuthenticationScheme,
            new ClaimsPrincipal(claimIdentity));
    
  • 完成此操作后,您可以使用
    [Authorize]
    属性标记其他actionmethods,例如:

    [Authorize(Roles = "User")]
    public IActionResult About() { ... }
    
    [Authorize(Roles = "Administrator")]
    public IActionResult Contact() { ... }
    
    现在,只有具有“管理员”角色的已登录用户才能访问联系人页面


    查看参考资料,了解所用中间件的更精细的配置。

    另一种基于我的数据库而不做任何修改的实现方法是使用声明和cookie。通过阅读以下文档,我成功地做到了这一点

    我只遇到了一个通过阅读解决的主要问题

    我还将添加登录方法和Startup.cs行,以便其他人可以看到如何使用它(如果文档不够的话)

    控制器登录方法

       [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Login(UserModel userModel)
        {
            if (_iUserBus.LoginUser(userModel))
            {
                var claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Name, userModel.Email),
                        new Claim(ClaimTypes.Role, _iUserBus.GetRole(userModel.Email)),
                    };
    
                ClaimsIdentity userIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
    
                var authProperties = new AuthenticationProperties
                {
                    IsPersistent = false,
                };
    
                await HttpContext.SignInAsync(principal, authProperties);
    
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("Password", "Email and/or Password wrong");
    
                return View();
            }
        }
    

    希望这对有需要的人有用。

    这确实不是实现安全性的方法。请阅读文档:是的,这个答案正是我想要的,因为我对我之前读到的内容有点困惑。我今天还和我的导师谈过,他告诉我关于基于Cookie和声明的同样事情。谢谢
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            });
    
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
            {
                options.LoginPath = "/Users/Login";
                options.LogoutPath = "/Users/Logout";
            });