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

时间:2019-06-30 10:26:44

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

具有用于ajax请求的带有authorize属性的控制器方法。当我未登录时发出请求时,我将重定向到登录页面。我需要一个未经授权的信息,而不是登录页面的数据。要更改此设置,我重写了“ 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;
    }

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

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

感谢您的帮助!

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

1 个答案:

答案 0 :(得分:0)

更多调查后,我找到了此解决方案:

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”

相关问题