Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net / ASP.NET Core Web API unauthorized requests returns 302 redirect response instead of 401

In ASP.Net / ASP.Net Core WebAPI,

When the client/browser tries to access a WebAPI endpoint which is decorated with [Authorized] attribute. It gets a 302-Found status code with a redirect response to the Login page, instead of 401-Unauthorized for an unauthorized request.

Note: I have noticed that Fail(AuthorizationContext context) method in AuthorizeAttribute filter sets the response code as 401-Unauthorized, but eventually browser gets a 302-Found response.

How can I send the 401 response instead of 302 ?

UPDATE: Update the question with ASP.NET Core

like image 830
Safeer Hussain Avatar asked May 23 '15 09:05

Safeer Hussain


1 Answers

Finally found the solution.

The redirection happens with the Cookie Authentication module. By default its LoginPath property is set to /Account/Login. If it is set to PathString.Empty, it will keep the status code as 401-Unauthorized without changing it to 302-Found.

Change CookieAuthenticationOptions in Startup.cs as follows:

public void ConfigureServices(IServiceCollection services)
{
    // Other configurations ...

    services.Configure<CookieAuthenticationOptions>(o =>
    {
        o.LoginPath = PathString.Empty;
    });

    // ...
}

XML documentation of LoginPath property:

The LoginPath property informs the middleware that it should change an outgoing 401 Unauthorized status code into a 302 redirection onto the given login path. The current url which generated the 401 is added to the LoginPath as a query string parameter named by the ReturnUrlParameter. Once a request to the LoginPath grants a new SignIn identity, the ReturnUrlParameter value is used to redirect the browser back to the url which caused the original unauthorized status code.

If the LoginPath is null or empty, the middleware will not look for 401 Unauthorized status codes, and it will not redirect automatically when a login occurs.


UPDATE: As @swdon pointed out, ASP.NET Core 2.x has a different way of doing this.

Here's the accepted answer from the link 1:

As of ASP.NET Core 2.x:

services.ConfigureApplicationCookie(options =>
{
    options.Events.OnRedirectToLogin = context =>
    {
        context.Response.StatusCode = 401;    
        return Task.CompletedTask;
    };
});
like image 198
Safeer Hussain Avatar answered Nov 07 '22 11:11

Safeer Hussain