【问题标题】:ASP.NET Core custom defined User Roles implementationASP.NET Core 自定义用户角色实现
【发布时间】:2018-09-14 13:26:25
【问题描述】:

我正在尝试定义 User Roles 的自定义方式,因为我的数据库的 User 表结构如下:


Role 是一个布尔值,所以如果它是真的用户是管理员,否则他是普通用户。


我知道我需要在 Startup.cs. 中声明 add.UseAuthorization() 并且我可以在 Controller 中添加属性 [Roles="Administrator"] / [Roles="User"] 但我我不确定如何定义要由 User 表中的 Role 列确定的角色。

我一直在搜索互联网,也阅读了有关政策的信息,但我认为这不是正确的实施方式。我在网上找到的所有内容都与某种 Identity 结构有关,但对于如何将其附加到我的 Role 列没有任何意义。

希望有人可以帮助我。谢谢!

【问题讨论】:

标签: asp.net-core-mvc roles asp.net-authorization


【解决方案1】:

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

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

  • 选择一种身份验证方案来登录用户(例如基于 Cookie,...)
  • 用户登录后,将设计的角色保存在 ClaimsPrincipal 对象中。这样[Authorize(Roles = "User")] 声明就可以接收到这一点。

您将在下面找到一个在 Visual Studio 中使用默认 ASP.NET Core 模板的基本示例。

  1. 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] 可以识别它

  1. 从数据库中获取您需要的值。你最终会得到一个bool。将其转换为角色Claim,并将其添加到ClaimsIdentity

    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] 属性标记其他操作方法,例如:

[Authorize(Roles = "User")]
public IActionResult About() { ... }

[Authorize(Roles = "Administrator")]
public IActionResult Contact() { ... }

现在,只有具有“管理员”角色的登录用户才能访问联系人页面。

查看this 资源以获取更精细的中间件配置。

【讨论】:

  • 是的,这个答案是我一直在寻找的,因为我对之前读到的内容有些困惑。我今天也和我的导师谈过,他告诉我关于 Cookie-based 和 Claims 的事情。谢谢!
【解决方案2】:

基于我的数据库而没有任何修改的另一种实现方式是使用声明和 Cookie。我已经设法阅读以下文件

Link One

Link Two

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

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

来自 Controller

Login 方法

   [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();
        }
    }

Startup.cs

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

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

【讨论】:

    猜你喜欢
    • 2023-02-21
    • 2023-03-16
    • 2015-07-21
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    相关资源
    最近更新 更多