【问题标题】:Authentication not working after editing Cookie options编辑 Cookie 选项后身份验证不起作用
【发布时间】:2019-11-11 10:14:52
【问题描述】:

在具有授权属性的 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-core asp.net-core-mvc asp.net-core-2.1 asp.net-core-identity


    【解决方案1】:

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

    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”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-19
      • 2021-05-26
      • 2012-09-06
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-03
      • 2012-10-04
      相关资源
      最近更新 更多