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?
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");
}
I figured it out. I was getting the JSON message when the LoginPath for the OwinStartup class was specified.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With