System.Web.Http.AuthorizeAttribute does not recognize custom role provider

In my MVC 4 Web API project, I have a role provider that works according to an attribute System.Web.Mvc.Authorize

on my Home System.Web.Mvc.Controller

.

In any System.Web.Http.ApiController

c, the System.Web.Http.Authorize

custom role provider is never called, always returning false. Is there a way to specify that the AuthorizeAttribute Web API takes over my role provider like MVC's AuthorizeAttribute?

Role provider:

public class CustomRoleProvider : RoleProvider
{        
    //Overriden methods
    public override string[] GetRolesForUser(string username)
    {
        //Always return "Master" for testing purposes
        return new string[] { "Master" };
    }

    public override bool IsUserInRole(string username, string roleName)
    {
        //Always return true for testing purposes
        return true;
    }

    //Other overridden method stubs...
}

      

Web.config:

<roleManager defaultProvider="CustomRoleProvider" enabled="true" cacheRolesInCookie="false" >
  <providers>
    <clear />
    <add name="CustomRoleProvider" type="MyApp.SecurityExtensions.CustomRoleProvider, MyApp" />
  </providers>
</roleManager>

      

+3


source to share


2 answers


This is not really an answer, but it might help:

Both attributes work by asking the current member. The MVC attribute uses HTTPContent.User, while the System.Web.http version uses Thread.CurrentPrincipal, but this difference is not significant.

I'm not very familiar with the web API, but I suspect that the RoleManagerModule is not working when the attribute is fired, or has not yet reached the PostAuthenticateRequest event, because in this case the module is replacing Pricipal.



Are you sure that some form of ASP authentication is required to use WebAPI? If you don't have a WebAPI project configured to require some sort of authentication, then obviously you never reach the PostAuthenticateRequest event, and thus the RoleManagerModule will never run.

The last possibility that comes to mind is that someting else replaces Principal after the RoleManagerModule does so. If possible, temporarily remove the System.Web.Http.AuthorizeAttribute, set a breakpoint in the controller, and determine which Thread.CurrentPrincipal class has. This can give you a hint where things went wrong.

+2


source


You will need to use System.Web. Http .AuthorizeAttribute for Web API controllers. Example: http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-membership-provider/



0


source







All Articles