Search code examples
c#angularjsrestasp.net-web-apiformsauthentication

Retrieving the Principal in a RESTful WebApi method


I am new to RESTful services using WebApi. I have a front-end web application that uses FormsAuthentication to authenticate users. I am able to use the User.Identity property without any problems in my MVC controller methods.

However, I want to use Angular to make Ajax calls from the browser to the Restful methods in WebApi. The problem occurs with the user principal in these methods - HttpRequestMessage.GetUserIdentity() always returns null. By contrast, Thread.CurrentPrincipal in these methods correctly returns the currently authenticated user identity. My WebApi controller is decorated with the Authorize attribute.

What am I missing that is stopping GetUserIdentity() from working? Here is my controller.

[Authorize]
public class CategoryController : ApiController
{
    public IEnumerable<ICategoryJson> Get(HttpRequestMessage request)
    {
        var user = request.GetUserPrincipal();                  // returns null
        var user1 = System.Threading.Thread.CurrentPrincipal;   // returns authenticated user identity

        return null;
    }
}

And here is my Ajax call.

$http.get("/api/Category", config).then(function (response) {
    Array.prototype.push.apply(service.list, response.data);
    service.listLoading = false;
});

Solution

  • MVC controller inherits from a different base class so that's why it works in the MVC controller and not the Web API.

    In Web API 2 you can use RequestContext.Principal or as you have used the Thread.CurrentPrincipal within your controller action to get the users Identity.

    I don't think this issue is related to the ajax or angular call. you can try calling the same MVC controller action from the angular code and it should still return the user's identity.