MVC Role Authorization

后端 未结 3 1412
抹茶落季
抹茶落季 2021-01-31 20:50

I am trying to implement a role authorization mechanism which checks the roles of the current logged in user, if the user is in the right role, he/she is allowed, else display e

3条回答
  •  星月不相逢
    2021-01-31 21:17

    Your original code was close, but the problem lies here:

    base.OnAuthorization(filterContext);
    

    Unconditionally calling the base class means you are requiring the decorated roles to be found in BOTH the UsersService and the built-in Role provider. If the role provider isn't configured to return the same set of roles (which they wouldn't if the default AuthorizeAttribute isn't sufficient for you) then this will obviously result in the Authorization test always returning false.

    Instead you could add a separate property to the derived Attribute such as

    public string RemoteRoles { get; set; }
    

    and replace

     List requiredRoles = Roles.Split(Convert.ToChar(",")).ToList();
    

    with:

     List requiredRoles = RemoteRoles.Split(Convert.ToChar(",")).ToList();
    

    And decorate your controller like such:

    [RoleAuthorization (RemoteRoles = "Client, Administrator")]
    

提交回复
热议问题