Search code examples
c#asp.net-coreasp.net-core-mvcasp.net-core-2.1asp.net-core-identity

Authentication not working after editing Cookie options


In have controller-methods for ajax-request with an authorize attribute. When I make a request when I'm not logged in, I get a redirect to the login page. I need an Unauthorized and not the Login page data. To change this I overridden the "OnRedirectToLogin" event.

Here is the Code:

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;
    }

All changes work, but when I try to log in on the default login-page, nothing happens.

What is the Problem there or have you a better option to achieve the same result without this problem?

Thanks for your help!

Update: I've kept looking in the time since the post has been online. Now I have found out that the login works, but the authentication on the controller apparently no longer.


Solution

  • After some more investigation I have found this solution:

    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;
                };
            });
    

    The decisive factor was to set only the "DefaultChallengeScheme"