Asp.net Identity 3 return 403 未经授权的请求而不是 WebAPI 调用的重定向

Asp.net Identity 3 return 403 Unauthorized request instead of redirect for WebAPI call

我在 Asp.net 核心项目中使用了 Asp.net Identity 3(仅针对 net451 编译。)

问题来了,当我使用 [Authorize] 标签调用 WebAPI 时,系统总是 return 登录 url 而不是未授权调用的 401。我想知道怎么做 return 401 ?

原来在startup.cs

services.AddIdentity<ApplicationUser, IdentityRole>()

更改为以下代码将解决此问题。

        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToAccessDenied = context => {
                        context.Response.StatusCode = 403;
                        return Task.FromResult(0);
                    },
                    OnRedirectToLogin = context =>
                    {
                        context.Response.StatusCode = 401;
                        return Task.FromResult(0);
                    }
                };
                options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
            })

您被重定向是因为 ApplicationCookie 默认将 AutomaticChallenge 设置为 true

要防止重定向,请使用:

options.Cookies.ApplicationCookie.AutomaticChallenge = false;

maxisam 的回答很有帮助,但情况又变了。 IdentityOptions 上不再有 Cookies 属性,但是,这有效:

services.ConfigureApplicationCookie(options =>
{
    options.Events = new CookieAuthenticationEvents
    {
        OnRedirectToAccessDenied = context =>
        {
            context.Response.StatusCode = 403;
            return Task.FromResult(0);
        },
        OnRedirectToLogin = context =>
        {
            context.Response.StatusCode = 401;
            return Task.FromResult(0);
        }
    };
});