12

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

4

1 回答 1

20

终于找到了解决办法。

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

Startup.csCookieAuthenticationOptions中的更改如下:

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

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

    // ...
}

属性的 XML 文档LoginPath

LoginPath 属性通知中间件它应该将传出的 401 Unauthorized 状态代码更改为到给定登录路径的 302 重定向。生成 401 的当前 url 作为由 ReturnUrlParameter 命名的查询字符串参数添加到 LoginPath。一旦对 LoginPath 的请求授予新的 SignIn 身份,ReturnUrlParameter 值将用于将浏览器重定向回导致原始未经授权状态代码的 url。

如果 LoginPath 为 null 或为空,则中间件不会查找 401 Unauthorized 状态码,并且不会在登录时自动重定向。


更新:正如@swdon 所指出的,ASP.NET Core 2.x有不同的方式来做到这一点。

这是链接 1中接受的答案:

ASP.NET Core 2.x开始:

services.ConfigureApplicationCookie(options =>
{
    options.Events.OnRedirectToLogin = context =>
    {
        context.Response.StatusCode = 401;    
        return Task.CompletedTask;
    };
});
于 2015-05-23T17:46:38.287 回答