加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

ASP.NET Core 2.0 Identity中的Cookies.ApplicationCookie.Autom

发布时间:2020-12-16 03:30:44 所属栏目:asp.Net 来源:网络整理
导读:我从ASP.NET Core 1.1升级到2.0,现在有401个未经授权的响应被更改为302重定向响应.这在以前是我在1.1中的一个问题,并通过以下代码进行了缓解: services.AddIdentityUser,IdentityRole(identityOptions ={ identityOptions.Cookies.ApplicationCookie.Automa
我从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()扩展在全局级别配置默认方案处理程序.

为了防止Identity注册的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;
    };
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读