Adding multiple OpenIdConnect authentication schemes to the services and choosing at runtime which to use

56 Views Asked by At

I have a Asp.net core mvc project that uses the OpenIdConnect authentication scheme with the Microsoft Identity platform. The way I add it is in my Startup class in ConfigureServices method like so:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
    // Removed everything else for briefity.
}

The AzureAd configuration section looks like this:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "mydomain.com",
  "ClientId": "X",
  "TenantId": "Y",
  "CallbackPath": "/signin-oidc"
}

This works splendidly and the [Authorize] attribute on the actions in the controllers prompt the user to log in using Microsoft account. But I want to be able to add multiple AzureAd config sections and decide at runtime which section to use to log in the user.

Example of how it might look like:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd1"));
    services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd2"));
    // Removed everything else for briefity.
}

and:

"AzureAd1": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "mydomain1.com",
  "ClientId": "X1",
  "TenantId": "Y1",
  "CallbackPath": "/signin-oidc"
},
"AzureAd2": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "mydomain2.com",
  "ClientId": "X2",
  "TenantId": "Y2",
  "CallbackPath": "/signin-oidc"
}

and then in the controller instead of decorating the methods with attribute [Authorize], or maybe keep it, I would do something like so:

[Authorize]
public IActionResult Login(string returnUrl)
{
    var x = GetX();
    var azureAdSettings = _azureAdSettings.GetSettings(x);
    // Set authentication based on the azureAdSettings for x.
}

Maybe it should be done in the constructor instead and set a scoped context. Is this even possible?

0

There are 0 best solutions below