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

限于喜欢 提交于 2019-12-09 05:54:32

问题


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


回答1:


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;
    };
});


来源:https://stackoverflow.com/questions/30411296/asp-net-asp-net-core-web-api-unauthorized-requests-returns-302-redirect-respon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!