【问题标题】:Asp.Net Core Identity - simple Authorization without Roles tableAsp.Net Core Identity - 没有角色表的简单授权
【发布时间】:2020-08-05 16:06:31
【问题描述】:

我正在尝试为我的应用程序开发一个简单的用户授权机制,而不使用特定的角色表。

User 实体有一个简单的 Role 枚举属性,我想在某些控制器上适当地装饰 Authorize 属性。

也许我在这里遗漏了一些东西,但是我怎样才能让框架知道用户在登录时或登录后的角色是什么

var result = await _signInManager.PasswordSignInAsync(usr, pwd, false, lockoutOnFailure: false);

然后使用Authorize 属性?

【问题讨论】:

    标签: asp.net-core-mvc authorization asp.net-identity asp.net-core-3.1


    【解决方案1】:

    UserManager.AddClaimAsync(TUser, Claim) method 可以帮助向用户添加指定的声明,您可以尝试以下代码 sn-p 来实现您的要求。

    var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
    
    if (result.Succeeded)
    {
        var user = await _userManager.FindByNameAsync(Input.Email);
    
        var userRole = CustomMethod_FindUserRole(Input.Email);
    
        await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, userRole));
    
        //...
    
        await _signInManager.RefreshSignInAsync(user);
    
    
        //...
    

    【讨论】:

    • 谢谢。我认为这应该是公认的答案,但也许您应该指定您必须正确实施 AddClaimAsync
    • _signInManager.PasswordSignInAsync 默认情况下是否添加任何其他声明?
    【解决方案2】:

    您可以使用身份服务器的 ProfileService 向特定用户添加角色声明。需要添加的地方

    claims.Add(new Claim("Role","Admin"));
    

    您还需要在您的 starup.cs 中实施政策

    services.AddAuthorization(options =>
        {
            options.AddPolicy("AdminCheck", policy =>
                              policy.RequireClaim("Role", "Admin"));
        });
    

    在你的动作方法或控制器上你需要把装饰器作为

    [Authorize(Policy = "AdminCheck")]
    public class VacationController : Controller
    {
        public ActionResult VacationBalance()
        {
        }
    }
    

    就是这样。

    【讨论】:

    • 谢谢。我试图做类似的事情,但我不明白应该在哪里传递声明。添加角色声明后,如何使用声明对象?
    猜你喜欢
    • 2020-09-24
    • 2020-03-02
    • 2021-09-04
    • 2017-12-01
    • 2021-02-27
    • 1970-01-01
    • 2019-09-17
    • 2020-05-18
    • 1970-01-01
    相关资源
    最近更新 更多