Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Identity: Web Api request fails authorization, returns 200 OK

I am getting up to speed on Asp.Net Identity in .NET 4.5. I setup a test app that registers, logs in, and attempts to make a call to an Api Controller that requires a Claim of "Admin":

[Authorize(Roles="Admin")]
public class WorkController : ApiController

When a request is made that does not have the Claim of "Admin", the Web Api still returns 200-OK, but with the JSON of: {Message:"Authorization has been denied for this request."}

This seems a little odd to me, since this does not represent successful request. I was expecting a 401 error. I am having trouble finding information on how to customize the response, or return a proper status code....I guess I should ask if 401 is even proper for this, or is the 200 the correct status code to use, and I should just handle it?

edit: For some reason it is now returning 401. Now I don't understand why I was getting the JSON message earlier if it was denied?

like image 876
Mike_G Avatar asked Apr 04 '14 18:04

Mike_G


2 Answers

The article referred to above is correct, however I think it doesn't cover the case where the API is being called by a 3rd party application rather than as an ajax request (Testing query["X-Requested-With"] etc).

This is my preference:

in Startup.Configuration() or Startup.ConfigureAuth():

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/LogOn"),
    Provider = new CookieAuthenticationProvider
    {
        OnApplyRedirect = ctx =>
        {
            if (!IsApiRequest(ctx.Request))
            {
                ctx.Response.Redirect(ctx.RedirectUri);
            }
        }
    }
});

private bool IsApiRequest(IOwinRequest request)
{
    return request.Uri.AbsolutePath.StartsWith("/api");
}
like image 36
Michael Ribbons Avatar answered Sep 27 '22 20:09

Michael Ribbons


I figured it out. I was getting the JSON message when the LoginPath for the OwinStartup class was specified.

like image 76
Mike_G Avatar answered Sep 27 '22 22:09

Mike_G