/// <summary> /// Gets an <see cref="AadIssuerValidator"/> for an authority. /// </summary> /// <param name="aadAuthority">The authority to create the validator for, e.g. https://login.microsoftonline.com/. </param> /// <returns>A <see cref="AadIssuerValidator"/> for the aadAuthority.</returns> /// <exception cref="ArgumentNullException">if <paramref name="aadAuthority"/> is null or empty.</exception> public AadIssuerValidator GetAadIssuerValidator(string aadAuthority) { if (string.IsNullOrEmpty(aadAuthority)) { throw new ArgumentNullException(nameof(aadAuthority)); } Uri.TryCreate(aadAuthority, UriKind.Absolute, out Uri? authorityUri); string authorityHost = authorityUri?.Authority ?? new Uri(Constants.FallbackAuthority).Authority; if (_issuerValidators.TryGetValue(authorityHost, out AadIssuerValidator? aadIssuerValidator)) { return(aadIssuerValidator); } // In the constructor, we hit the Azure AD issuer metadata endpoint and cache the aliases. The data is cached for 24 hrs. IssuerMetadata issuerMetadata = _configManager.GetConfigurationAsync().ConfigureAwait(false).GetAwaiter().GetResult(); // Add issuer aliases of the chosen authority to the cache IEnumerable <string> aliases = issuerMetadata.Metadata .Where(m => m.Aliases.Any(a => string.Equals(a, authorityHost, StringComparison.OrdinalIgnoreCase))) .SelectMany(m => m.Aliases) .Append(authorityHost) // For B2C scenarios, the alias will be the authority itself .Distinct(); _issuerValidators[authorityHost] = new AadIssuerValidator(aliases); return(_issuerValidators[authorityHost]); }
/// <summary> /// Retrieves the AadIssuerValidator for a given authority /// </summary> /// <param name="aadAuthority"></param> /// <returns></returns> public static AadIssuerValidator ForAadInstance(string aadAuthority) { if (issuerValidators.ContainsKey(aadAuthority)) { return(issuerValidators[aadAuthority]); } else { string authorityHost = new Uri(aadAuthority).Authority; // In the constructor, we hit the Azure AD issuer metadata endpoint and cache the aliases. The data is cached for 24 hrs. string AzureADIssuerMetadataUrl = "https://login.microsoftonline.com/common/discovery/instance?authorization_endpoint=https://login.microsoftonline.com/common/oauth2/v2.0/authorize&api-version=1.1"; ConfigurationManager <IssuerMetadata> configManager = new ConfigurationManager <IssuerMetadata>(AzureADIssuerMetadataUrl, new IssuerConfigurationRetriever()); IssuerMetadata issuerMetadata = configManager.GetConfigurationAsync().Result; // Add issuer aliases of the chosen authority string authority = authorityHost ?? FallBackAuthority; var aliases = issuerMetadata.Metadata.Where(m => m.Aliases.Any(a => a == authority)).SelectMany(m => m.Aliases).Distinct(); AadIssuerValidator issuerValidator = new AadIssuerValidator(aliases); issuerValidators.Add(authority, issuerValidator); return(issuerValidator); } }