简体   繁体   English

MVC自定义授权数据库属性

[英]MVC Custom Authorize Attribute From Database

I made my own custom Role table in my database and I wanted to also create a custom authorize attribute along with it. 我在数据库中创建了自己的自定义角色表,并且还希望创建一个自定义授权属性。

Here is what I have so far, but I'm not really sure how to proceed: 到目前为止,这是我所拥有的,但是我不确定如何进行:

    private List<RoleModel> Roles;
    private IRoleRepository repo;
    private ICustomerRepository cust;


    public bool CheckRoles(string UserId)
    {
        try
        {
            Roles = repo.GetAll().ToList();
            CustomerModel Customer = cust.Get(UserId);
            int CustomerRole = Customer.RoleId;
            RoleModel role = Roles.First(x => x.id == CustomerRole);


        }
        catch(Exception e)
        {
            return false;
        }
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);
        string UserId = filterContext.HttpContext.User.Identity.GetUserId();



    } 

If anyone can help me finish this I would greatly appreciate it. 如果有人可以帮助我完成这项工作,我将不胜感激。

Thanks! 谢谢!

I think that create a custom AuthorizeAttribute is not a good idea. 我认为创建自定义AuthorizeAttribute不是一个好主意。 It is a good practice to use the standard AuthorizeAttribute. 最好使用标准AuthorizeAttribute。

It is a common case to have its own Role table. 拥有自己的角色表是一种常见的情况。 It is better to override how to set the roles of the identity of your principal and to use the Roles property of AuthorizeAttribute. 最好重写如何设置主体身份的角色并使用AuthorizeAttribute的Roles属性。 Set the role as a claim once when the user is logging; 用户登录时,将角色设置为声明。 it will be better than retrieve the role from database in the custom Authorize attribute at each request. 它将比在每次请求时从自定义Authorize属性中的数据库检索角色更好。 Set your claim CalimTypes.Role, and then protect your controllers/actions with : 设置您的CalimTypes.Role声明,然后使用以下命令保护您的控制器/动作:

[Authorize(Roles = "admin")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM