Cookies.ApplicationCookie.AutomaticChallenge = false in ASP.



我从 ASP.NET Core 1.1升级到2.0,现在有401个未经授权的响应更改为302重定向响应。这以前在 1.1 中对我来说是一个问题,并通过以下代码得到了缓解:

services.AddIdentity<User, IdentityRole>(identityOptions =>
{
identityOptions.Cookies.ApplicationCookie.AutomaticChallenge = false;
})

但是,identityOptions上不再有Cookies属性。

我也尝试添加以下内容(并且还注意到我以前在我的应用程序中不需要此扩展方法(:

services.AddCookieAuthentication(cookieAuthenticationOptions => {
cookieAuthenticationOptions.LoginPath = ""; // also tried null
cookieAuthenticationOptions.AccessDeniedPath = ""; // also tried null
cookieAuthenticationOptions.LogoutPath = ""; // also tried null
});

该代码似乎对默认重定向路径或行为没有影响。如何在Core 2.0中防止这些重定向?

如 https://github.com/aspnet/Announcements/issues/262 中所述,现在必须使用services.AddAuthentication()扩展在全局级别配置默认方案处理程序。

若要防止标识注册的 cookie 处理程序处理质询,请将DefaultChallengeScheme替换为对应于其他处理程序的方案(例如 JWT 持有者处理程序(。

services.AddIdentity<User, IdentityRole>();
services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
});

如果 - 无论出于何种原因 - 选择不同的处理程序不适合您,则必须使用services.ConfigureApplicationCookie()注册自定义CookieAuthenticationEvents.(On)RedirectToLogin事件以更改 Identity 返回"未经授权的响应"的方式。

下面是返回 401 响应的示例:

services.ConfigureApplicationCookie(options =>
{
options.Events.OnRedirectToLogin = context =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
});

最新更新