Skip to content

Instantly share code, notes, and snippets.

@brianpursley
Created October 11, 2022 19:04
Show Gist options
  • Save brianpursley/79112f82b06711ca3f5ba8e54e01b42c to your computer and use it in GitHub Desktop.
Save brianpursley/79112f82b06711ca3f5ba8e54e01b42c to your computer and use it in GitHub Desktop.
Use different SignUpSignIn Azure AD B2C policies, depending on the hostname, allowing you to provide SSO for specific companies, without having to provide a button for each SSO integration on the main login page
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
namespace AuthTest.Extensions;
public static class ServiceCollectionExtensions
{
// USAGE:
//
// 1. Add the following line in Program.cs, after your call to AddMicrosoftIdentityWebApp:
// builder.Services.AddAlternateSignUpSignInPolicies(builder.Configuration.GetSection("AzureAdB2C"));
//
// 2. Add a AlternateSignUpSignInPolicyIds subsection your appsettings.json, mapping host names to policy IDs:
// "AzureAdB2C": {
// ... OTHER FIELDS OMITTED ...
// "AlternateSignUpSignInPolicyIds": {
// "thirdparty.local": "B2C_1_signin_ExampleCo"
// }
// },
//
public static void AddAlternateSignUpSignInPolicies(this IServiceCollection services, IConfigurationSection configurationSection)
{
var defaultPolicyId = configurationSection["SignUpSignInPolicyId"];
var alternateSignUpSignInPolicyIds = configurationSection
.GetSection("AlternateSignUpSignInPolicyIds")
.GetChildren()
.ToDictionary(config => config.Key.ToLower(), config => config.Value);
services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = context =>
{
var host = context.Request.Host.Host.ToLower();
var altPolicyId = alternateSignUpSignInPolicyIds.GetValueOrDefault(host);
if (altPolicyId != null)
{
context.ProtocolMessage.IssuerAddress = context.ProtocolMessage.IssuerAddress
.Replace(defaultPolicyId, altPolicyId, StringComparison.OrdinalIgnoreCase);
}
return Task.CompletedTask;
}
};
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment