Search code examples
c#asp.net-core-identityasp.net-core-2.2asp.net-core-configuration

ASP.NET Core Identity does not redirect to correct logon pages


Configured this way it is not working.

    services
        .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.ExpireTimeSpan = TimeSpan.FromMinutes(5);

            options.LoginPath = $"/logon";
            options.LogoutPath = $"/logoff";
            options.AccessDeniedPath = $"/accessdenied";
            options.SlidingExpiration = true;
        })

configured this way it is working :

    services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.Name = "Caldr.Auth";
        options.LoginPath = $"/logon";
        options.LogoutPath = $"/logoff";
        options.AccessDeniedPath = $"/accessdenied";
    });

    services
        .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)

I would expect both to have the same behavior. Apprantly not. Bug or I did not got how to configure it ? :-)

Any thoughts.


Solution

  • At the time of posting my question I had identity framework configured/added too. So it might have been the mix of several factors that may it not work properly.

    The working solution:

    CONFIG:

    var authenticationBuilder = services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = $"/logon";
            options.LogoutPath = $"/logoff";
            options.AccessDeniedPath = $"/accessdenied";
        });
    ConfigureSocialLogins(authenticationBuilder);
    

    The actual logon (i.e. writing the cookies is done via)

    private async Task SignInUser(AppUser appUser)
            {
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier, appUser.Email),
                    new Claim(ClaimTypes.Name, appUser.Displayname ?? appUser.Email),
                    new Claim(ClaimTypes.Email, appUser.Email),
                };
                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
    
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, new AuthenticationProperties());
            }
    

    Take note of all the usages of CookieAuthenticationDefaults.AuthenticationScheme.