ASP.NET Core 2.0 禁用自动质询 [英] ASP.NET Core 2.0 disable automatic challenge

查看:27
本文介绍了ASP.NET Core 2.0 禁用自动质询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将我的 ASP.NET Core 项目升级到 2.0 后,尝试访问受保护的端点不再返回 401,而是重定向到(不存在的)端点以尝试让用户进行身份验证.

After upgrading my ASP.NET Core project to 2.0, attempts to access protected endpoints no longer returns 401, but redirects to an (non-existing) endpoint in an attempt to let the user authenticate.

所需的行为是应用程序简单地返回 401.以前我会在配置身份验证时设置 AutomaticChallenge = false,但根据 这篇文章 该设置不再相关(实际上它不再存在).

The desired behaviour is for the application simply to return a 401. Previously I would set AutomaticChallenge = false when configuring authentication, but according to this article the setting is no longer relevant (in fact it doesn't exist anymore).

我的身份验证是这样配置的:

My authentication is configured like this:

Startup.cs.ConfigureServices():

Startup.cs.ConfigureServices():

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(o =>
                {
                    o.Cookie.Name = options.CookieName;
                    o.Cookie.Domain = options.CookieDomain;
                    o.SlidingExpiration = true;
                    o.ExpireTimeSpan = options.CookieLifetime;
                    o.TicketDataFormat = ticketFormat;
                    o.CookieManager = new CustomChunkingCookieManager();
                });

配置():

app.UseAuthentication();

如何禁用自动质询,以便在用户未通过身份验证时应用程序返回 401?

How can I disable automatic challenge, so that the application returns 401 when the user is not authenticated?

推荐答案

正如其他一些答案所指出的,不再有使用 cookie 身份验证关闭自动质询的设置.解决方案是覆盖OnRedirectToLogin:

As pointed out by some of the other answers, there is no longer a setting to turn off automatic challenge with cookie authentication. The solution is to override OnRedirectToLogin:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
         {                 
             options.Events.OnRedirectToLogin = context =>
             {
                 context.Response.Headers["Location"] = context.RedirectUri;
                 context.Response.StatusCode = 401;
                 return Task.CompletedTask;
             };
         });

这在未来可能会改变:https://github.com/aspnet/Security/issues/1394

这篇关于ASP.NET Core 2.0 禁用自动质询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆