ASP.Net / ASP.NET Core Web API 未经授权的请求 returns 302 重定向响应而不是 401

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

在 ASP.Net / ASP.Net 核心 WebAPI 中,

当 client/browser 尝试访问用 [Authorized] 属性修饰的 WebAPI 端点时。它获得一个 302-Found 状态代码,并带有对登录页面的重定向响应,而不是 401-Unauthorized 未经授权的请求.

注意:我注意到 Fail(AuthorizationContext context) 方法在 AuthorizeAttribute 过滤器中将响应代码设置为 401-Unauthorized,但最终浏览器会收到 302-Found 响应。

如何发送 401 响应而不是 302

更新:更新问题 ASP.NET Core

终于找到解决办法了。

重定向发生在 Cookie 身份验证 模块中。默认情况下,它的 LoginPath 属性 设置为 /Account/Login。如果设置为PathString.Empty,它会保持状态码为401-Unauthorized而不改变为302-Found.

Startup.cs中的CookieAuthenticationOptions改为:

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

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

    // ...
}

XML LoginPath 的文档 属性:

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.


更新: 正如@swdon 指出的那样,ASP.NET Core 2.x 有不同的做法这个。

这是 接受的答案:

截至 ASP.NET 核心 2.x:

services.ConfigureApplicationCookie(options =>
{
    options.Events.OnRedirectToLogin = context =>
    {
        context.Response.StatusCode = 401;    
        return Task.CompletedTask;
    };
});