chrisjsherm
chrisjsherm

Reputation: 1329

System.Web.Http.AuthorizeAttribute not recognizing custom role provider

In my MVC 4 Web API project, I have a custom role provider that works as designed via System.Web.Mvc.Authorize attribute on my Home System.Web.Mvc.Controller.

On any System.Web.Http.ApiController with System.Web.Http.Authorize the custom role provider never gets called, always returning false. Is there a way to specify that the Web API AuthorizeAttribute pick up my custom role provider like the MVC 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>

Upvotes: 3

Views: 3203

Answers (2)

Joe
Joe

Reputation: 36

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

Both attributes work by querying the current pricipal. The MVC attribute uses HTTPContent.User, while the System.Web.http version uses Thread.CurrentPrincipal, but that difference is minor.

I'm not really familar with Web API, but I suspect that the RoleManagerModule is not running by the time the attribute fires, or you have not yet reached the PostAuthenticateRequest event, because in that event the Module replaces the Pricipal.

Are you sure you have some form of ASP authentication required for your WebAPI usage? If you don't have your WebAPI project configured to require some form of authentication, then obviously you will never reach the PostAuthenticateRequest event, and thus the RoleManagerModule will never kick-in.

The last possibility that comes to mind is that someting else is replacing the Principal after the RoleManagerModule does so. If possible, temporarally remove the System.Web.Http.AuthorizeAttribute, set a breakpoint in the controller, and detemine what class Thread.CurrentPrincipal has. That might give you a hint as to where it went wrong.

Upvotes: 2

Kiran
Kiran

Reputation: 57949

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

Upvotes: 0

Related Questions