c# - ASP.NET Core 2.0 禁用自动质询

标签 c# authentication asp.net-core asp.net-core-mvc

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

应用程序所需的行为只是返回 401。以前我会在配置身份验证时设置 AutomaticChallenge = false,但根据 this article该设置不再相关(实际上它不再存在)。

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

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?

最佳答案

正如其他一些答案所指出的,不再有关闭 cookie 身份验证自动挑战的设置。解决方案是覆盖 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

关于c# - ASP.NET Core 2.0 禁用自动质询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45878166/

相关文章:

.net - ASP.NET Core 1.0 F#项目

c# - 有没有理由我不应该通过测试他们的产品来测试一组 0 的变量?

c# - 将按键事件路由到其他控件

powershell - Azure PowerShell 如何使用基于用户名/密码的身份验证?

iphone - 重新登录时 Facebook iOS Api 调用失败,但 isSessionValid 为 YES

c# - 在数据注释验证错误消息中隐藏底层属性名称

c# - 在添加新力之前从 Rigidbody 移除先前的力

c# - 列计数与第 1 行的值计数不匹配 C#

java - 如何通过以编程方式设置用户名和密码来连接到 ActiveMQ 服务器?

html - 我将样式设置为移动但图像不会移动