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

查看:68
本文介绍了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();
                });

Configure():

Configure():

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天全站免登陆