-
Notifications
You must be signed in to change notification settings - Fork 219
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Sample documentation on how to authenticate with Azure AD AND Azure B2C in one application .net core 3.x #549
Comments
Would the following help, @UM001 ? (adapted to Web Apps) |
Thank you. I will give it a try. I have no webapi's as given in this example by the way.
|
I modified for now using webapi, but mvc. I get System.InvalidOperationException: 'Scheme already exists: Cookies' ` services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
|
I have difficulities understanding how this should work. I have no errors now in the startup, but getting it to work is another thing. I did not add 4 schemes, only 2?
a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn" asp-route-scheme="AzureAd">Sign in ad ` services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAd",
I would expect only to do this: |
It keeps going to azure b2c, not to azure ad anymore:
|
I think the issue lies in the fact that the configuration options for 2 authentication schemes are overwritten and/or only 1 is allowed.
I am looking at the Woodgrove sample and your code is more or less the same...would be nice to have Woodgrove work with your library as that is exacly what I am looking for.....but with less code like yours.
|
I confirm something is wrong in your code. Not exactly sure where as I have no net 5.0 to add a default asp .netcore next to your code to see how that goes. If I add this piece of code from Woodgrove sample I get in my accountcontrollers 2 different (but still erronous) calls to Azure AD and Azure B2C, but as setup is not 100% both do not exactly work. ` private static void ConfigureAuthentication(IConfiguration configuration, IServiceCollection services)
|
I have it working with Woodgrove as example. Not using this library as I believe the MicrosoftIdentityOptions and scheme can only be one instead of multiple. Hope you get the idea so I can replace all this code with this library in future. 404 and cookie expiration to be investigated now. private void ConfigureAuthentication(IServiceCollection services)
{
var authenticationBuilder = services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
//options.DefaultAuthenticateScheme = Constants.AzureAdB2c;
});
ConfigureCookieAuthentication(authenticationBuilder);
ConfigureB2CAuthentication(services, authenticationBuilder);
ConfigureB2BAuthentication(services, authenticationBuilder);
}
private void ConfigureCookieAuthentication(AuthenticationBuilder authenticationBuilder)
{
authenticationBuilder.AddCookie(options => { options.ExpireTimeSpan = new TimeSpan(7, 0, 0, 0); });
}
private void ConfigureB2BAuthentication(IServiceCollection services, AuthenticationBuilder builder)
{
var openIdConnectScheme = Constants.AzureAd;
var authenticationOptions = new MicrosoftIdentityOptions();
Configuration.Bind(openIdConnectScheme, authenticationOptions);
builder.AddOpenIdConnect(openIdConnectScheme, options => {
Configuration.Bind(openIdConnectScheme, options);
options.Authority = $"https://login.microsoftonline.com/{authenticationOptions.TenantId}/v2.0";
options.CallbackPath = new PathString(authenticationOptions.CallbackPath);
options.ClientId = authenticationOptions.ClientId;
//options.ConfigurationManager =
//options.Events = CreateB2BOpenIdConnectEvents();
options.SignedOutCallbackPath = new PathString(authenticationOptions.SignedOutCallbackPath);
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = ClaimConstants.PreferredUserName
};
options.ProtocolValidator.NonceLifetime = TimeSpan.FromHours(1);
});
}
private void ConfigureB2CAuthentication(IServiceCollection services, AuthenticationBuilder builder)
{
var openIdConnectScheme = Constants.AzureAdB2c;
var authenticationOptions = new MicrosoftIdentityOptions();
Configuration.Bind(openIdConnectScheme, authenticationOptions);
builder.AddOpenIdConnect(openIdConnectScheme, options => {
Configuration.Bind(openIdConnectScheme, options);
options.Authority = $"{authenticationOptions.Instance}tfp/{authenticationOptions.Domain}/{authenticationOptions.SignUpSignInPolicyId}";
options.CallbackPath = new PathString(authenticationOptions.CallbackPath);
options.ClientId = authenticationOptions.ClientId;
//options.ConfigurationManager =
//options.Events = CreateB2COpenIdConnectEvents();
options.Scope.Remove("profile");
options.SignedOutCallbackPath = new PathString(authenticationOptions.SignedOutCallbackPath);
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = ClaimConstants.Name,
};
options.ProtocolValidator.NonceLifetime = TimeSpan.FromHours(1);
});
}`
AccountController:
`/// <summary>
/// Handles the user sign-out.
/// </summary>
/// <param name="scheme">Authentication scheme.</param>
/// <returns>Sign out result.</returns>
[HttpGet("{scheme?}")]
public async Task<IActionResult> SignOut([FromRoute] string scheme)
{
if (User.Identity.IsAuthenticated)
{
var authenticateResult = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
var callbackUrl = Url.Page("/Account/SignedOut", pageHandler: null, values: null, protocol: Request.Scheme);
await HttpContext.SignOutAsync(
authenticateResult.Properties.Items[".AuthScheme"],
new AuthenticationProperties()
{
RedirectUri = callbackUrl
});
return new EmptyResult();
}
return RedirectToHome();
} |
See also #173 |
Hi, is there any reference to an example using both Identity providers in one MVC app? I too am having the same issue where B2C overwrites AzureAD Authentication when trying to login to an MVC app configured for both Azure AD and B2C through separate links. |
It's on the backlog, @Kev8144 to build such a sample. We don't have it yet |
Hi, I'm having the same question. I'd like to use Azure AD and Azure AD B2C together in one app. My code in Startup:
Now, when calling Edit: Ok it seems I'm assuming wrong and the default |
@sven5 : I agree. I believe that we have a bug, as the options are configured independently of the authentication schemes. |
Duplicate of #955 |
Included in 1.11.0 release and documentation here. |
So now I'm trying to implement this solution in one of my apps.
I don't need any downstream API. Edit: my sample code
Now when clicking on a link with |
@jmprieur Thanks, I already looked into this. However, it's not working on my side. I'd like to be able that users of both Azure AD and Azure AD B2C are able to login to my application. |
@sven5 : did you see this sample? https://github.com/AzureAD/microsoft-identity-web/tree/master/tests/MultipleAuthSchemes |
@jmprieur Yes, I'm currently trying to find the cause of my issues. Perhaps I have a misconfiguration. |
@jmprieur I've created a minimal repo sample here: https://github.com/sven5/MultipleAuthTest Thanks! edit: I tried several combinations now and couldn't get it working |
Update. After lots of trial & error and looking into the source code I've finally found a working solution. The key is to use Cookie authentication as default and passing the value of My code now looks like: services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.ExpireTimeSpan = new TimeSpan(7, 0, 0, 0);
});
services.AddAuthentication()
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"), Microsoft.Identity.Web.Constants.AzureAd, null);
services.AddAuthentication()
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAdB2C"), Microsoft.Identity.Web.Constants.AzureAdB2C, null); |
Thanks for sharing your findings, @sven5. |
Is there a sample anywhere of how this can be used in a Blazor Server app? I've configured the Startup.cs as shown above, but am getting "No authenticationScheme was specified, and there was no DefaultChallengeScheme found". How should the preferred authenticationScheme be specified ? |
@Contengo Blazor Server is the same as plain ASP.NET Core and Razor pages. Just have a look at my sample above. I have it working with a Blazor Server app. |
Thanks for the reply - not sure if it's the reason it's not working for me but my use case is slightly different: I'm trying to enable it to call a downstream API. The scenario is a Blazor App which calls an ASP.NET Core API - I'm trying to enable them to be accessed from both B2C and B2B logins. Trying to figure out the best architecture for that to save implementing as two instances of each one. If anyone can get a sample of that working that would be brilliant.... |
@Contengo For your scenario there is a nice wiki article here. |
Hi @Contengo I did an example for this here: The APIs need to use the right scheme as well Greetings Damien |
Many thanks @damienbod and @sven5 - with those inputs I think it's now nailed. I must say this enforced separation of B2B from B2C identities does make life a whole lot more complicated than it needs to be - I do wish MS would drop it and converge them! |
@Contengo Nice that it's working now at your side. For application developers, there also is another way to go: You could use B2C even for your B2B accounts to allow logging in. But you have to adjust the custom policies, which is an extra complex step. You could read more about here: https://docs.microsoft.com/en-us/azure/active-directory-b2c/identity-provider-azure-ad-single-tenant?pivots=b2c-custom-policy |
Could someone please talk about this issue? My Startup.cs authentication code: services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options => services.AddAuthentication() The statement where exception occurs: Exception: InnerException {"IDW10503: Cannot determine the cloud Instance. The provided authentication scheme was ''. Microsoft.Identity.Web inferred 'Cookies' as the authentication scheme. Available authentication schemes are 'Cookies,AzureAd'. See https://aka.ms/id-web/authSchemes. "} System.Exception {System.InvalidOperationException} I really appreciate any help you can provide. |
Description of the issue
Can you show an example of how to create an application on which employees from an Azure AD can sign-in and with another url users from an Azure B2C instance? I can have them both work separately, but not together.
The text was updated successfully, but these errors were encountered: