Search code examples
asp.net-corecookiesopenid-connect

ASP.NET Core 3.1 Use both OpenIDConnect and Custom Cookie Authentication


I have an existing application that makes use of Cookie Authentication, and would like to add the ability to authenticate users using Active Directory. The current application uses Cookie based authentication and custom authorisation - roles in a database.

I am adding bits from example located here:

Add sign-in with Microsoft to an ASP.NET Core web app

When I run the application I get an error:

System.InvalidOperationException: Scheme already exists: Cookies

What is the correct way to configure OpenIdConnect and Cookie Authentication.

// STEP 1 Basic Cookie Auth

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
            {
                options.LoginPath = "/Auth";
                options.AccessDeniedPath = "/Home/AccessDenied";
                options.Cookie.IsEssential = true;
                options.SlidingExpiration = true;
                options.ExpireTimeSpan = TimeSpan.FromSeconds(day/2.0);
                options.Cookie.HttpOnly = true; // not accessible via JavaScript
                options.Cookie.Name = "login_token";

                options.TicketDataFormat = new CustomJwtDataFormat(
                    SecurityAlgorithms.HmacSha256,
                    tokenValidationParameters);
            });

// STEP 2 OpenID Connect Auth

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"), "OpenIdConnect", "Cookies", true);

I am not able to find any examples using both Cookie Authentication and OpenID Connect. Is this possible? Allowing users to login selectively using Active Directory authentication, or local authentication (details stored in local database).

After changing the "Cookie" name, get's rid of the error message, but breaks the local authorisation, e.g.

When a valid Username and Password is given, I typically authorise the login.

HttpContext.Response.Cookies.Append("login_token", token, GetCookieOptions());

Currently with OpenIDConnect configured User.Identity.IsAuthenticated remains false.


Solution

  • According to the error messages, it tell you that you have multiple Scheme which named cookies.

    According to the AddMicrosoftIdentityWebApp Method document, you could find the third parameter name is the cookieScheme.

    The cookie-based scheme name to be used. By default it uses "Cookies".

    But you have already set this name at above, so you should use other one. For example: "ADCookies".

    Like below:

    services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"), "OpenIdConnect", "ADCookies", true);