Skip to content

Add multiple AAD authentication options using AddMicrosoftIdentityWebAppAuthentication not possible #971

Closed

Description

Which version of Microsoft Identity Web are you using?
Microsoft Identity Web 1.6.0

Where is the issue?

  • Web app
    • Sign-in users
    • Sign-in users and call web APIs
  • Web API
    • Protected web APIs (validating tokens)
    • Protected web APIs (validating scopes)
    • Protected web APIs call downstream web APIs
  • Token cache serialization
    • In-memory caches
    • Session caches
    • Distributed caches
  • Other (please describe)

I have an app which needs to support authentication using multiple AAD's, but if I try to call AddMicrosoftIdentityWebAppAuthentication multiple times it seams that only the last one takes affect, but I get a "Unable to unprotect the message.State" exception although I've set different CallbackPath.

Is there an other way to do this?

  "azuread1": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "azuread1.onmicrosoft.com",
    "TenantId": "xxxxx",
    "ClientId": "xxxxxx",
    "ClientSecret": "xxxxx",
    "CallbackPath": "/signin-oidc/azuread1",
    "SignedOutCallbackPath": "/signout-callback-oidc"
  },
 "azuread2": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "azuread2.onmicrosoft.com",
    "TenantId": "yyyyy",
    "ClientId": "yyyyy",
    "ClientSecret": "yyyyy",
    "CallbackPath": "/signin-oidc/azuread2",
    "SignedOutCallbackPath": "/signout-callback-oidc"
  },
services.AddMicrosoftIdentityWebAppAuthentication(configuration: Configuration,
                                                              configSectionName: "azuread1",
                                                              openIdConnectScheme: "azuread1",
                                                              cookieScheme: null);

 services.AddMicrosoftIdentityWebAppAuthentication(configuration: Configuration,
                                                              configSectionName: "azuread2",
                                                              openIdConnectScheme: "azuread2",
                                                              cookieScheme: null);

If I try to logging using azuread1 it will say the user dows not exist in azuread2.onmicrosoft.com, while if I log in using azuread2 I get an "Unable to unprotect the message.State" exception.

Activity

  1. jmprieur commented on Feb 17, 2021

    @jmprieur
    Collaborator

    Mikael Håkansson (@wmmihaa) : this is duplicate of #955

  2. wmmihaa commented on Feb 17, 2021

    @wmmihaa
    Author

    Mikael Håkansson (@wmmihaa) : this is duplicate of #955

    Not sure it is as this relates to multiple auth schemes of the same type

  3. wmmihaa commented on Feb 22, 2021

    @wmmihaa
    Author

    Is there a plan to support integration with multiple AAD using AddMicrosoftIdentityWebAppAuthentication?

  4. jmprieur commented on Feb 23, 2021

    @jmprieur
    Collaborator

    Mikael Håkansson (@wmmihaa) : AddMicrosoftIdentityWebAppAuthentication is a shortcut for the simple case where you don't want to specify the scheme, whereas the multi AAD scenario is the very case where you want to control the scheme.
    You'll want to do;

    AddAuthentication(defaultScheme)
     .AddMicrosoftIdentityWebApp(configSection1, scheme1)
    
    AddAuthentication()
     .AddMicrosoftIdentityWebApp(configSection2, scheme2)

    We think we'll work on supporting this in 1.18.

  5. wmmihaa commented on Feb 23, 2021

    @wmmihaa
    Author

    I think the problem is in SignInManager.ConfigureExternalAuthenticationProperties which will always route to the same AAD independently of the provider...

    public IActionResult OnPost(string provider, string returnUrl = null)
    {
        // Request a redirect to the external login provider.
        var redirectUrl = Url.Page("./ExternalLogin", pageHandler: "Callback", values: new { returnUrl });
        var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
        return new ChallengeResult(provider, properties);
    }
    

    The line above will always route to the last added Authentication ...

    StartUp.cs:

    services.AddAuthentication(("azuread1)
        .AddMicrosoftIdentityWebApp(Configuration.GetSection("azuread1"), "azuread1", null);
    
    services.AddAuthentication()
        .AddMicrosoftIdentityWebApp(Configuration.GetSection("azuread2"), "azuread2", null);
    

    Each of the line above work by it self, but not together

    Let me know if you want med to demo this through a teams session

  6. wmmihaa commented on Feb 24, 2021

    @wmmihaa
    Author

    I've made short video to better explain the scenario and issue.
    https://youtu.be/SSuciNOnt-0
    hth

  7. wmmihaa commented on Feb 25, 2021

    @wmmihaa
    Author

    I've raised the issue in the aspnetcore repo: dotnet/aspnetcore#30472

  8. wmmihaa commented on Mar 3, 2021

    @wmmihaa
    Author

    Any news on this?
    btw...I would not consider this an enhancement but a bug

    dotnet/aspnetcore#30472 is closed so this is no longer duplicate.

  9. jmprieur commented on Mar 4, 2021

    @jmprieur
    Collaborator

    Mikael Håkansson (@wmmihaa) : we are currently working on higher priority very requested features (performance and resilience of the token cache adapters, and rotation of certificates)
    This would be next.

  10. wmmihaa commented on Mar 4, 2021

    @wmmihaa
    Author

    Jean-Marc Prieur (@jmprieur) Thank you for the feedback. We will continue working on other things while we wait.

  11. modified the milestones: 1.9.0, 1.10.0 on Mar 31, 2021
  12. 4 remaining items

  13. added this to the 1.11.0 milestone on May 14, 2021
  14. jennyf19 commented on May 24, 2021

    @jennyf19
    Collaborator
  15. wmmihaa commented on May 24, 2021

    @wmmihaa
    Author

    Thank you jennyf19

  16. sven5 commented on Jul 8, 2021

    @sven5

    Mikael Håkansson (@wmmihaa) Do you get it working with the new version?
    I'm not successful. I already tried several combinations, still no luck.
    Could you provide some demo code?

    Thanks!

  17. wmmihaa commented on Jul 8, 2021

    @wmmihaa
    Author

    Hi Sven,
    Yes it works for me. We're using v 1.14.0 (Microsoft.Identity.Web & Microsoft.Identity.Web.UI):

    Startup.cs - ConfigureServices

    foreach (var section in Configuration.GetSection("azureAd").GetChildren())
    {
        services.AddAuthentication()
        .AddMicrosoftIdentityWebApp(section, section.Key, null);
    }

    appsettings.json

      "azureAd": {
        "AAD1": {
          "Instance": "XXX",
          "Domain": "XXX",
          "TenantId": "XXX",
          "ClientId": "XXX",
          "CallbackPath": "/signin-oidc/aad1"
        },
        "AAD2": {
          "Instance": "https://login.microsoftonline.com/",
          "Domain": "XXX",
          "TenantId": "XXX",
          "ClientId": "XXX",
          "ClientSecret": "XXX",
          "CallbackPath": "/signin-oidc/aad2"
        }
      }

    HTH

  18. sven5 commented on Jul 9, 2021

    @sven5

    Ok my scenario is a little different. I'd like to use AAD and AAD B2C together in one web app.

    services.AddAuthentication()
                        .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"), Microsoft.Identity.Web.Constants.AzureAd, "cookiesAd");
    
    services.AddAuthentication()
                       .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAdB2C"), Microsoft.Identity.Web.Constants.AzureAdB2C, "cookiesB2C");

    My problem is that after logging in by using AAD the User is not authenticated in the app. Both authentication methods never work at the same time

  19. sven5 commented on Jul 9, 2021

    @sven5

    Ok, now I've found my mistake. The important thing is passing the value of null to the cookieScheme parameter and setting Cookie Authentication as default.

  20. Faisal-developer commented on Aug 13, 2022

    @Faisal-developer

    Mikael Håkansson (@wmmihaa) Is it working ? And how you differentiate that which user will be part of which tenant ?

    How you modified this below code

    public IActionResult OnPost(string provider, string returnUrl = null)
    {
    // Request a redirect to the external login provider.
    var redirectUrl = Url.Page("./ExternalLogin", pageHandler: "Callback", values: new { returnUrl });
    var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
    return new ChallengeResult(provider, properties);
    }

  21. wmmihaa commented on Aug 15, 2022

    @wmmihaa
    Author

    Hi Faisal,
    Yes I got it working.

    And how you differentiate that which user will be part of which tenant ?

    There are a couple of ways you can do this. Default, you'd allow the user to select which identity provider to use. In my case,I persist each AAD configuration in the database together with the email domain and as the user types their email address I redirect based on the domain.

    How you modified this below code...

    Your code looks good

  22. Faisal-developer commented on Aug 15, 2022

    @Faisal-developer

    Mikael Håkansson (@wmmihaa) Got it. You are using this for mobile app ? I meaning azure ad is integrated with mobile app or using web app ?

  23. wmmihaa commented on Aug 15, 2022

    @wmmihaa
    Author

    It's a web application

  24. Faisal-developer commented on Aug 15, 2022

    @Faisal-developer

    Mikael Håkansson (@wmmihaa) Do you have any idea how it will work for flutter mob app ?

  25. wmmihaa commented on Aug 15, 2022

    @wmmihaa
    Author

    Sorry, I have not worked with flutter.

  26. rafaelcaviquioli commented on Nov 29, 2022

    @rafaelcaviquioli

    I have the following configuration, AzureAdB2C is set as default, but when I open the application, I'm forwarded to AzureAdB2C signin page.

    I would expect that when the user tries to open a not public page, it is forwarded to the auth provider configured in the default scheme.

    services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(options =>
        {
            configuration.Bind("AzureAdB2C", options);
            options.Events ??= new OpenIdConnectEvents();
            options.ResponseType = OpenIdConnectResponseType.Code;
            options.Scope.Add(options.ClientId);
        }, subscribeToOpenIdConnectMiddlewareDiagnosticsEvents: true, cookieScheme: null);
    
    services.AddAuthentication()
        .AddMicrosoftIdentityWebApp(options =>
        {
            configuration.Bind("AzureAdB2C", options);
            // Replace with invitation custom policy and callback urls 
            configuration.Bind("AzureAdB2CInvitation", options);
    
            options.ResponseType = OpenIdConnectResponseType.Code;
            options.Scope.Add(options.ClientId);
            options.Events ??= new OpenIdConnectEvents();
            
            options.Events.OnRedirectToIdentityProvider += async (context) =>
            {
                var idTokenHint = context.Request.Query["id_token_hint"];
                if (!string.IsNullOrEmpty(idTokenHint))
                {
                    context.ProtocolMessage.IdTokenHint = idTokenHint;
                }
                await Task.CompletedTask.ConfigureAwait(false);
            };
        }, subscribeToOpenIdConnectMiddlewareDiagnosticsEvents: true, openIdConnectScheme: InvitationScheme, cookieScheme: null);

    I also have this policy configured:

    services
        .AddMvcCore()
        .AddApiExplorer()
        .AddAuthorization(options =>
        {
            options.DefaultPolicy = new AuthorizationPolicyBuilder()
                .AddAuthenticationSchemes(OpenIdConnectDefaults.AuthenticationScheme, AuthenticationExtensions.InvitationScheme)
                .RequireAuthenticatedUser()
                .Build();
            
            options.AddPolicy(AuthenticationExtensions.SmAccessPolicy, policy =>
            {
                policy.AddAuthenticationSchemes(
                    OpenIdConnectDefaults.AuthenticationScheme,
                    AuthenticationExtensions.InvitationScheme
                );
                policy.RequireAssertion(context => context.User.HasClaim(c => c.Type == "extension_roles" && c.Value.Split(",").Contains("product.sm")));
            });
        })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions