Diego Mijelshon
Diego Mijelshon

Reputation: 52745

Web API with Forms authentication and roles

I have a MVC4 web application set up, which uses Forms authentication and Web API for interaction. All API controllers use the [Authorize] attribute.

This was working just fine out of the box, until we started adding role support. Instead of implementing a full-fledged RoleProvider, I added a list of roles to the ticket's UserData, and created the following module:

public class SecurityModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        var roleManager = (RoleManagerModule)context.Modules["RoleManager"];
        roleManager.GetRoles += GetRoles;
    }

    void GetRoles(object sender, RoleManagerEventArgs e)
    {
        var user = e.Context.User;
        if (user.Identity.IsAuthenticated && !(user is MyCustomPrincipal))
        {
            var roles = GetRolesFromFormsAuthCookie();
            if (roles != null)
                e.Context.User = new MyCustomPrincipal(user.Identity, roles,
                                                       otherData);
        }
        e.RolesPopulated = true;
    }
}

This works flawlessly for MVC calls. For API, however, even though GetRoles gets called, when it reaches the corresponding method, it's back to GenericPrincipal.

How can I make this work with Web API too? Do I have to create a DelegatingHandler?

I'm also storing some custom data in my Principal, which might be a reason not to rely on just a RoleProvider (since I'd end up with a RolePrincipal), although I could just store that in the request context.


Update: I've now added a DelegatingHandler that does the same as the IHttpModule and sets Thread.CurrentPrincipal. Is this a reasonable approach?

Upvotes: 0

Views: 483

Answers (1)

Pablo Cibraro
Pablo Cibraro

Reputation: 3959

Have you tried to set the Thread.CurrentPrincipal in the HttpModule as well ?. You can also use a Katana handler, which will work for both, ASP.NET MVC and ASP.NET Web API.

Upvotes: 1

Related Questions