MVC Role Authorization

时光毁灭记忆、已成空白 提交于 2019-12-02 17:18:46

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<Role> 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.

fmoliveira

If you're using MVC 5 you have to enable lazy loading in your DbContext by putting the following line in your DbContext initialisation.

this.Configuration.LazyLoadingEnabled = true;

In MVC 5 default project you'll add it to ApplicationDbContext.cs file.

I'm not sure if this is particular to MVC 5, to Identity 2.0, or affect other versions. I'm using this setup and enabling lazy loading make all the default role schema works. See https://stackoverflow.com/a/20433316/2401947 for more info.

Additionally, if you're using ASP.NET Identity 2.0 default permission schema, you don't have to implement Application_AuthenticateRequest as Darren mentioned. But if you're using custom authorisation tables, then you have to implement it as well.

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<String> requiredRoles = Roles.Split(Convert.ToChar(",")).ToList();

with:

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

And decorate your controller like such:

[RoleAuthorization (RemoteRoles = "Client, Administrator")]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!