Search code examples
asp.net-coreauthenticationmicrosoft-identity-web

Multiple Authentication in ASP.NET Core


The authentication (Cookie) of my project is set as below,

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
            .AddCookie(options =>
            {
                options.ClaimsIssuer = "xxx.admin";
                options.Cookie.HttpOnly = true;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                options.LoginPath = "/Login/Index/";
                options.AccessDeniedPath = "/Account/Unauthorized/";
                options.Cookie.SameSite = SameSiteMode.Strict;
            });

and I configured second authentication option (OpenIdConnect) in different project as below,

         services.AddRazorPages().AddMvcOptions(options =>
        {
            var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
            options.Filters.Add(new AuthorizeFilter(policy));
        }).AddMicrosoftIdentityUI();

        services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApp(options =>
        {
            Configuration.Bind("AzureActiveDirectoryConnection", options);

            options.Events ??= new OpenIdConnectEvents();
            options.Events.OnTokenValidated += OnTokenValidated;
            options.Events.OnTicketReceived += OnTicketReceived;
            //options.Events.OnRedirectToIdentityProvider += OnRedirectToIdentityProvider;
        });

Now, I need to combine them to support multiple authentication types in my app. How can I do that?


Solution

  • Step 1:

    Add compliant Microsoft.Identity.Web and Microsoft.Identity.Web.UI NuGet Packages to your project.

    Step 2:

    Add following lines after .AddCookie(options => ..) method.

    .Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureActiveDirectoryConnection"), "OpenIdConnect", "_Cookies", true);
    
    services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options => {
    
        options.Events ??= new OpenIdConnectEvents();
        options.Events.OnTokenValidated += OnTokenValidated;
        options.Events.OnTicketReceived += OnTicketReceived;
        options.Events.OnRedirectToIdentityProvider += OnRedirectToIdentityProvider;
    });
    
    // This is for Azure AD SignIn and SignOut buttons' functions
    services.AddRazorPages().AddMvcOptions(options => { }).AddMicrosoftIdentityUI();
    
    // We say "I have multiple authentication schemes" to the app here
    services.AddAuthorization(options =>
    {
        var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme);
        defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
        options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();
    });
    

    Briefly, you add second authentication option here and specify its events you need and bind Azure AD clientId, tenantId, etc. which comes from AppSettings file, such as:

    "AzureActiveDirectoryConnection": {
      "Instance": "https://login.microsoftonline.com/",
      "Domain": "YourDomainName.onmicrosoft.com",
      "TenantId": "YourTenantId",
      "ClientId": "YourClientId",
      "CallbackPath": "/signin-oidc",
      "SignedOutCallbackPath ": "/signout-oidc"
    }