在ASP.NET Core 2.0 Identity中,Cookies.ApplicationCookie.AutomaticChallenge = false的替代方案是什么?

9

我从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://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x?view=aspnetcore-2.1 - Der_Meister
1个回答

16

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

为了防止Identity注册的Cookie处理程序处理挑战,请用与不同处理程序对应的方案(例如JWT承载程序)替换DefaultChallengeScheme

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;
    };
});

在Core 1.1中,我使用现有的cookie处理程序实现来响应我的控制器中的[Authorize]属性(这是我假设现有的Challenge逻辑被调用以将cookie值与用户数据库进行比较的地方)。然而,我想要做的唯一修改是在失败时简单地返回401而不是重定向,并保留所有Identity现有的Cookie挑战逻辑。 - Matthew Steven Monkan
正如我所说的,AutomaticChallenge已经不再存在了,而默认的挑战方案必须在全局级别进行注册。如果您不更改DefaultChallengeScheme,那么在使用[Authorize]时将触发默认的cookie处理程序。如果由于某种原因选择其他处理程序不是您的选择,那么您将不得不使用services.ConfigureApplicationCookie()来注册自定义的CookieAuthenticationEvents.RedirectToLogin事件,以更改Identity返回“未经授权的响应”的方式(例如返回401响应)。 - Kévin Chalet
@KévinChalet 我使用了不同的DefaultChallengeScheme,但是在ConfigureApplicationCookie中的OnRedirectToLogin事件没有触发,你知道在.NET Core 3.1中捕获此事件的其他选项吗? - Alex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接