首页 > 解决方案 > 编辑 Cookie 选项后身份验证不起作用

问题描述

在具有授权属性的 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;
    }

所有更改都有效,但是当我尝试在默认登录页面上登录时,什么也没有发生。

那里的问题是什么,或者您有更好的选择来在没有这个问题的情况下达到相同的结果吗?

谢谢你的帮助!

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

标签: c#asp.net-coreasp.net-core-mvcasp.net-core-2.1asp.net-core-identity

解决方案


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

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”


推荐阅读