编辑 Cookie 选项后身份验证不起作用

Authentication not working after editing Cookie options

在具有授权属性的 ajax 请求中有控制器方法。当我在未登录的情况下发出请求时,我会重定向到登录页面。我需要一个未经授权的而不是登录页面数据。为了改变这一点,我覆盖了 "OnRedirectToLogin" 事件。

代码如下:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
        {
            options.LoginPath = "/Identity/Account/Login";
            options.Events.OnRedirectToLogin = ctx => Test(ctx);
        });


private Task Test(RedirectContext<CookieAuthenticationOptions> ctx)
    {
        if (ctx.Request.ContentType != null && ctx.Response.StatusCode == (int) HttpStatusCode.OK)
        {
            if (ctx.Request.ContentType.Contains("application/json"))
            {
                ctx.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
            }
        }
        else
        {
            ctx.Response.Redirect(ctx.RedirectUri);
        }

        return Task.CompletedTask;
    }

所有更改都有效,但是当我尝试在默认登录页面上登录时,没有任何反应。

那里有什么问题,或者您有更好的选择来实现相同的结果而没有这个问题?

感谢您的帮助!

更新: 自 post 上线以来,我一直在寻找时间。现在我发现登录有效,但控制器上的身份验证显然不再有效。

经过更多调查,我找到了这个解决方案:

services.AddAuthentication(options =>
        {
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;

        }).AddCookie(options =>
        {
            options.LoginPath = "/Identity/Account/Login";
            options.Events.OnRedirectToLogin = ctx =>
            {
                if (ctx.Request.ContentType != null && ctx.Response.StatusCode == (int) HttpStatusCode.OK)
                {
                    if (ctx.Request.ContentType.Contains("application/json"))
                    {
                        ctx.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
                    }
                }
                else
                {
                    ctx.Response.Redirect(ctx.RedirectUri);
                }

                return Task.CompletedTask;
            };
        });

决定性因素是只设置"DefaultChallengeScheme"