MVC Role Authorization

后端 未结 3 1405
抹茶落季
抹茶落季 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:24

    Since I had the roles of the users in the database I had to check against the database so I included this method in the global.asax

    protected void Application_AuthenticateRequest(object sender, EventArgs args)
        {
            if (Context.User != null)
            {
                IEnumerable roles = new UsersService.UsersClient().GetUserRoles(
                                                        Context.User.Identity.Name);
    
    
                string[] rolesArray = new string[roles.Count()];
                for (int i = 0; i < roles.Count(); i++)
                {
                    rolesArray[i] = roles.ElementAt(i).RoleName;
                }
    
                GenericPrincipal gp = new GenericPrincipal(Context.User.Identity, rolesArray);
                Context.User = gp;
            }
        }
    

    Then I could use the normal

    [Authorize(Roles = "Client, Administrator")]
    

    On top of the actionResult methods in the controllers

    This worked.

提交回复
热议问题