3
votes

I'm working on building a WebAPI AccountController with basic account functionality like LogIn, LogOut, Register, etc.

The top of my controller is decorated with the [System.Web.Http.Authorize] attribute.

In the following method, the user that is authenticated is my local system user unless I decorate the method with "AllowAnonymous":

    // GET/api/isAuthenticated
    // [System.Web.Http.AllowAnonymous]
    [System.Web.Http.HttpGet]
    public HttpResponseMessage IsAuthenticated()
    {
        if (User.Identity.IsAuthenticated)
        {
            var userProfile = _service.GetUserProfile(WebSecurity.CurrentUserId);
            return Request.CreateResponse(HttpStatusCode.OK, userProfile);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.OK, false);
        }
    }

From what I understand, AllowAnonymous tells the controller to not apply the Authorize attribute to the given method. Since I'm building a web application, I never want to authorize against local credentials.

I pulled this code from the MVC SPA template so I'm wondering - how can this be changed to Authorize against the locally stored user credentials, instead of the system user, when [AllowAnonymous] isn't used?

1
Look in your web.config, the authorization config section describes the authorization scheme. It sounds like you are set to anonymous currently. - asawyer
Also bear in mind that there's no concept of a "session" in Web API. This is by design, as Web API follows REST. HTTP is a stateless protocol, so some sort of authentication or authorization (token, for example) must be included in the headers for each and every request to an authorized view. - Chris Pratt
@asawyer - I just looked and I have the authentication set to Forms, though if I hover over "User.Identity" the authenticationType is listed as "Negotiate" instead of "Forms" - so it's pulling my system credentials. Any idea where else this could be configured? - RobVious
@ChrisPratt - thanks for the heads up Chris. - RobVious

1 Answers

1
votes

When using WebAPI you should authenticate your users via HTTP Basic Authorization, its an HTTP standard for authorization. If you are logging via aspx page you should set your authorization in config section to forms authentication and if not, then you should add http authorization headers in your webapi calls.

WebAPI controller is different then normal controller and so are its authentication mechanisms.