using System.Globalization; using System.Text; using System.Xml.Linq; using Fluid; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace OpenIddict.Client.WebIntegration.Generators; [Generator] public sealed class OpenIddictClientWebIntegrationGenerator : IIncrementalGenerator { public void Initialize(IncrementalGeneratorInitializationContext context) { var files = context.AdditionalTextsProvider.Where(static file => string.Equals(Path.GetFileName(file.Path), "OpenIddictClientWebIntegrationProviders.xml", StringComparison.OrdinalIgnoreCase)); context.RegisterSourceOutput(files, static (context, file) => { var parser = new FluidParser(); var document = XDocument.Load(file.Path, LoadOptions.None); context.AddSource( "OpenIddictClientWebIntegrationBuilder.generated.cs", SourceText.From(GenerateBuilderMethods(parser, document), Encoding.UTF8)); context.AddSource( "OpenIddictClientWebIntegrationConfiguration.generated.cs", SourceText.From(GenerateConfigurationClasses(parser, document), Encoding.UTF8)); context.AddSource( "OpenIddictClientWebIntegrationConstants.generated.cs", SourceText.From(GenerateConstants(parser, document), Encoding.UTF8)); context.AddSource( "OpenIddictClientWebIntegrationHelpers.generated.cs", SourceText.From(GenerateHelpers(parser, document), Encoding.UTF8)); context.AddSource( "OpenIddictClientWebIntegrationSettings.generated.cs", SourceText.From(GenerateSettings(parser, document), Encoding.UTF8)); }); static string GenerateBuilderMethods(FluidParser parser, XDocument document) { var template = parser.Parse(@"#nullable enable #pragma warning disable CS0618 using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Claims; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using OpenIddict.Client; using OpenIddict.Client.WebIntegration; using OpenIddict.Extensions; using static OpenIddict.Client.WebIntegration.OpenIddictClientWebIntegrationConstants; namespace Microsoft.Extensions.DependencyInjection; public sealed partial class OpenIddictClientWebIntegrationBuilder { {% for provider in providers %} /// /// Adds a new {{ provider.display_name }} client registration. {% if provider.documentation -%} /// For more information, read the documentation. {% endif -%} /// /// The delegate used to configure the OpenIddict/{{ provider.display_name }} options. /// The instance. {% if provider.obsolete -%} [Obsolete(""This provider is no longer supported and will be removed in a future version."")] {% endif -%} public OpenIddictClientWebIntegrationBuilder Add{{ provider.name }}(Action configuration) { ArgumentNullException.ThrowIfNull(configuration); var registration = new OpenIddictClientRegistration { ProviderSettings = new OpenIddictClientWebIntegrationSettings.{{ provider.name }}(), ProviderType = ProviderTypes.{{ provider.name }} }; configuration(new OpenIddictClientWebIntegrationBuilder.{{ provider.name }}(registration)); Services.Configure(options => options.Registrations.Add(registration)); return this; } {% endfor %} {% for provider in providers %} /// /// Exposes the necessary methods required to configure the {{ provider.display_name }} integration. /// {% if provider.obsolete -%} [Obsolete(""This provider is no longer supported and will be removed in a future version."")] {% endif -%} public sealed partial class {{ provider.name }} { /// /// Initializes a new instance of . /// /// The client registration. public {{ provider.name }}(OpenIddictClientRegistration registration) => Registration = registration ?? throw new ArgumentNullException(nameof(registration)); /// /// Gets the client registration. /// [EditorBrowsable(EditorBrowsableState.Never)] public OpenIddictClientRegistration Registration { get; } /// /// Adds one or more client authentication methods to the list of client authentication methods that can be negotiated for this provider. /// /// The client authentication methods. /// Note: explicitly configuring the allowed client authentication methods is NOT recommended in most cases. /// The instance. [EditorBrowsable(EditorBrowsableState.Advanced)] public {{ provider.name }} AddClientAuthenticationMethods(params string[] methods) { ArgumentNullException.ThrowIfNull(methods); Registration.ClientAuthenticationMethods.UnionWith(methods); return this; } /// /// Adds one or more code challenge methods to the list of code challenge methods that can be negotiated for this provider. /// /// The code challenge methods. /// Note: explicitly configuring the allowed code challenge methods is NOT recommended in most cases. /// The instance. [EditorBrowsable(EditorBrowsableState.Advanced)] public {{ provider.name }} AddCodeChallengeMethods(params string[] methods) { ArgumentNullException.ThrowIfNull(methods); Registration.CodeChallengeMethods.UnionWith(methods); return this; } /// /// Adds one or more grant types to the list of grant types that can be negotiated for this provider. /// /// The grant types. /// Note: explicitly configuring the allowed grant types is NOT recommended in most cases. /// The instance. [EditorBrowsable(EditorBrowsableState.Advanced)] public {{ provider.name }} AddGrantTypes(params string[] types) { ArgumentNullException.ThrowIfNull(types); Registration.GrantTypes.UnionWith(types); return this; } /// /// Adds one or more response modes to the list of response modes that can be negotiated for this provider. /// /// The response modes. /// Note: explicitly configuring the allowed response modes is NOT recommended in most cases. /// The instance. [EditorBrowsable(EditorBrowsableState.Advanced)] public {{ provider.name }} AddResponseModes(params string[] modes) { ArgumentNullException.ThrowIfNull(modes); Registration.ResponseModes.UnionWith(modes); return this; } /// /// Adds one or more response types to the list of response types that can be negotiated for this provider. /// /// The response types. /// Note: explicitly configuring the allowed response types is NOT recommended in most cases. /// The instance. [EditorBrowsable(EditorBrowsableState.Advanced)] public {{ provider.name }} AddResponseTypes(params string[] types) { ArgumentNullException.ThrowIfNull(types); Registration.ResponseTypes.UnionWith(types); return this; } /// /// Adds one or more scopes to the list of requested scopes, if applicable. /// /// The scopes. /// The instance. public {{ provider.name }} AddScopes(params string[] scopes) { ArgumentNullException.ThrowIfNull(scopes); Registration.Scopes.UnionWith(scopes); return this; } /// /// Disables pushed authorization requests for this client registration. When pushed authorization /// requests are disabled, PAR is not used by the OpenIddict client, even if the remote authorization /// server exposes a pushed authorization endpoint. If the authorization server requires using PAR, /// an exception is automatically thrown when starting an interactive authentication challenge. /// /// The instance. public {{ provider.name }} DisablePushedAuthorizationRequests() { Registration.DisablePushedAuthorizationRequests = true; return this; } /// /// Sets the issuer that will be attached to the /// instances created by the OpenIddict client stack for this provider. /// /// The claims issuer. /// The instance. public {{ provider.name }} SetClaimsIssuer(string issuer) { ArgumentException.ThrowIfNullOrEmpty(issuer); Registration.ClaimsIssuer = issuer; return this; } /// /// Sets the provider name. /// /// The provider name. /// The instance. public {{ provider.name }} SetProviderName(string name) { ArgumentException.ThrowIfNullOrEmpty(name); Registration.ProviderName = name; return this; } /// /// Sets the provider display name. /// /// The provider display name. /// The instance. public {{ provider.name }} SetProviderDisplayName(string name) { ArgumentException.ThrowIfNullOrEmpty(name); Registration.ProviderDisplayName = name; return this; } /// /// Sets the registration identifier. /// /// The registration identifier. /// The instance. public {{ provider.name }} SetRegistrationId(string identifier) { ArgumentException.ThrowIfNullOrEmpty(identifier); Registration.RegistrationId = identifier; return this; } /// /// Sets the client identifier. /// /// The client identifier. /// The instance. public {{ provider.name }} SetClientId(string identifier) { ArgumentException.ThrowIfNullOrEmpty(identifier); Registration.ClientId = identifier; return this; } /// /// Sets the client secret, if applicable. /// /// The client secret. /// The instance. public {{ provider.name }} SetClientSecret(string secret) { ArgumentException.ThrowIfNullOrEmpty(secret); Registration.ClientSecret = secret; return this; } /// /// Sets the client type (typically, ""public"" or ""confidential""). /// /// The client type. /// The instance. public {{ provider.name }} SetClientType(string type) { ArgumentException.ThrowIfNullOrEmpty(type); Registration.ClientType = type; return this; } /// /// Sets the post-logout redirection URI, if applicable. /// /// /// Note: the post-logout redirection URI is automatically added to /// . /// /// The post-logout redirection URI. /// The instance. public {{ provider.name }} SetPostLogoutRedirectUri(Uri uri) { ArgumentNullException.ThrowIfNull(uri); Registration.PostLogoutRedirectUri = uri; return this; } /// /// Sets the post-logout redirection URI, if applicable. /// /// /// Note: the post-logout redirection URI is automatically added to /// . /// /// The post-logout redirection URI. /// The instance. public {{ provider.name }} SetPostLogoutRedirectUri([StringSyntax(StringSyntaxAttribute.Uri)] string uri) { ArgumentException.ThrowIfNullOrEmpty(uri); return SetPostLogoutRedirectUri(new Uri(uri, UriKind.RelativeOrAbsolute)); } /// /// Sets the redirection URI, if applicable. /// /// /// Note: the redirection URI is automatically added to /// . /// /// The redirection URI. /// The instance. public {{ provider.name }} SetRedirectUri(Uri uri) { ArgumentNullException.ThrowIfNull(uri); Registration.RedirectUri = uri; return this; } /// /// Sets the redirection URI, if applicable. /// /// /// Note: the redirection URI is automatically added to /// . /// /// The redirection URI. /// The instance. public {{ provider.name }} SetRedirectUri([StringSyntax(StringSyntaxAttribute.Uri)] string uri) { ArgumentException.ThrowIfNullOrEmpty(uri); return SetRedirectUri(new Uri(uri, UriKind.RelativeOrAbsolute)); } {% for environment in provider.environments %} /// /// Configures the provider to use the ""{{ environment.name }}"" environment. /// /// The instance. public {{ provider.name }} Use{{ environment.name }}Environment() { Registration.Get{{ provider.name }}Settings().Environment = OpenIddictClientWebIntegrationConstants.{{ provider.name }}.Environments.{{ environment.name }}; return this; } {% endfor %} {% for setting in provider.settings %} {% if setting.collection %} /// /// Configures {{ setting.description }}. /// /// {{ setting.description | capitalize }}. /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Add{{ setting.property_name }}(params {{ setting.clr_type }}[] {{ setting.parameter_name }}) { ArgumentNullException.ThrowIfNull({{ setting.parameter_name }}); Registration.Get{{ provider.name }}Settings().{{ setting.property_name }}.UnionWith({{ setting.parameter_name }}); return this; } {% else %} {% case setting.clr_type %} {% when 'ECDsaSecurityKey' %} /// /// Configures {{ setting.description }}. /// /// {{ setting.description | capitalize }}. /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Set{{ setting.property_name }}(ECDsaSecurityKey {{ setting.parameter_name }}) { ArgumentNullException.ThrowIfNull({{ setting.parameter_name }}); if ({{ setting.parameter_name }}.PrivateKeyStatus is PrivateKeyStatus.DoesNotExist) { throw new ArgumentException(SR.GetResourceString(SR.ID0055), nameof({{ setting.parameter_name }})); } Registration.Get{{ provider.name }}Settings().{{ setting.property_name }} = {{ setting.parameter_name }}; return this; } #if NET /// /// Configures {{ setting.description }}. /// /// /// The PEM-encoded Elliptic Curve Digital Signature Algorithm (ECDSA) signing key. /// /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Set{{ setting.property_name }}(string key) => Set{{ setting.property_name }}(key.AsMemory()); /// /// Configures {{ setting.description }}. /// /// /// The PEM-encoded Elliptic Curve Digital Signature Algorithm (ECDSA) signing key. /// /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Set{{ setting.property_name }}(ReadOnlyMemory key) => Set{{ setting.property_name }}(key.Span); /// /// Configures {{ setting.description }}. /// /// /// The PEM-encoded Elliptic Curve Digital Signature Algorithm (ECDSA) signing key. /// /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Set{{ setting.property_name }}(ReadOnlySpan key) { if (key.IsEmpty) { throw new ArgumentException(SR.GetResourceString(SR.ID0346), nameof(key)); } var algorithm = ECDsa.Create(); try { algorithm.ImportFromPem(key); } catch { algorithm.Dispose(); throw; } return Set{{ setting.property_name }}(new ECDsaSecurityKey(algorithm)); } #endif {% when 'Uri' %} /// /// Configures {{ setting.description }}. /// /// {{ setting.description | capitalize }}. /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Set{{ setting.property_name }}(Uri {{ setting.parameter_name }}) { ArgumentNullException.ThrowIfNull({{ setting.parameter_name }}); if (!{{ setting.parameter_name }}.IsAbsoluteUri || OpenIddictHelpers.IsImplicitFileUri({{ setting.parameter_name }})) { throw new ArgumentException(SR.GetResourceString(SR.ID0144), nameof({{ setting.parameter_name }})); } Registration.Get{{ provider.name }}Settings().{{ setting.property_name }} = {{ setting.parameter_name }}; return this; } /// /// Configures {{ setting.description }}. /// /// {{ setting.description | capitalize }}. /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Set{{ setting.property_name }}(string {{ setting.parameter_name }}) { ArgumentException.ThrowIfNullOrEmpty({{ setting.parameter_name }}); return Set{{ setting.property_name }}(new Uri({{ setting.parameter_name }}, UriKind.RelativeOrAbsolute)); } {% when 'X509Certificate2' %} /// /// Configures {{ setting.description }}. /// /// {{ setting.description | capitalize }}. /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Set{{ setting.property_name }}(X509Certificate2 {{ setting.parameter_name }}) { ArgumentNullException.ThrowIfNull({{ setting.parameter_name }}); if (!{{ setting.parameter_name }}.HasPrivateKey) { throw new ArgumentException(SR.GetResourceString(SR.ID0061), nameof({{ setting.parameter_name }})); } Registration.Get{{ provider.name }}Settings().{{ setting.property_name }} = {{ setting.parameter_name }}; return this; } /// /// Configures {{ setting.description }}. /// /// The assembly containing the certificate. /// The name of the embedded resource. /// The password used to open the certificate. /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Set{{ setting.property_name }}(Assembly assembly, string resource, string? password) // Note: ephemeral key sets are currently not supported on macOS. => Set{{ setting.property_name }}(assembly, resource, password, OperatingSystem.IsMacOS() ? X509KeyStorageFlags.MachineKeySet : X509KeyStorageFlags.EphemeralKeySet); /// /// Configures {{ setting.description }}. /// /// The assembly containing the certificate. /// The name of the embedded resource. /// The password used to open the certificate. /// An enumeration of flags indicating how and where to store the private key of the certificate. /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Set{{ setting.property_name }}( Assembly assembly, string resource, string? password, X509KeyStorageFlags flags) { ArgumentNullException.ThrowIfNull(assembly); ArgumentException.ThrowIfNullOrEmpty(resource); using var stream = assembly.GetManifestResourceStream(resource) ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0064)); return Set{{ setting.property_name }}(stream, password, flags); } /// /// Configures {{ setting.description }}. /// /// The stream containing the certificate. /// The password used to open the certificate. /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Set{{ setting.property_name }}(Stream stream, string? password) // Note: ephemeral key sets are currently not supported on macOS. => Set{{ setting.property_name }}(stream, password, OperatingSystem.IsMacOS() ? X509KeyStorageFlags.MachineKeySet : X509KeyStorageFlags.EphemeralKeySet); /// /// Configures {{ setting.description }}. /// /// The stream containing the certificate. /// The password used to open the certificate. /// An enumeration of flags indicating how and where to store the private key of the certificate. /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Set{{ setting.property_name }}(Stream stream, string? password, X509KeyStorageFlags flags) { ArgumentNullException.ThrowIfNull(stream); using var buffer = new MemoryStream(); stream.CopyTo(buffer); var certificate = X509Certificate2.GetCertContentType(buffer.ToArray()) switch { X509ContentType.Pkcs12 => X509CertificateLoader.LoadPkcs12(buffer.ToArray(), password, flags), _ => throw new InvalidOperationException(SR.GetResourceString(SR.ID0454)) }; return Set{{ setting.property_name }}(certificate); } /// /// Configures {{ setting.description }}. /// /// The thumbprint of the certificate used to identify it in the X.509 store. /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} [UnsupportedOSPlatform(""linux"")] public {{ provider.name }} Set{{ setting.property_name }}(string thumbprint) { ArgumentException.ThrowIfNullOrEmpty(thumbprint); return Set{{ setting.property_name }}( GetCertificate(StoreLocation.CurrentUser, thumbprint) ?? GetCertificate(StoreLocation.LocalMachine, thumbprint) ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066))); static X509Certificate2? GetCertificate(StoreLocation location, string thumbprint) { using var store = new X509Store(StoreName.My, location); store.Open(OpenFlags.ReadOnly); return store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false) .Cast() .SingleOrDefault(); } } /// /// Configures {{ setting.description }}. /// /// The thumbprint of the certificate used to identify it in the X.509 store. /// The name of the X.509 store. /// The location of the X.509 store. /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Set{{ setting.property_name }}(string thumbprint, StoreName name, StoreLocation location) { ArgumentException.ThrowIfNullOrEmpty(thumbprint); using var store = new X509Store(name, location); store.Open(OpenFlags.ReadOnly); return Set{{ setting.property_name }}( store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false) .Cast() .SingleOrDefault() ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0066))); } {% when 'bool' %} /// /// Configures {{ setting.description }}. /// /// {{ setting.description | capitalize }}. /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Set{{ setting.property_name }}(bool {{ setting.parameter_name }}) { Registration.Get{{ provider.name }}Settings().{{ setting.property_name }} = {{ setting.parameter_name }}; return this; } {% else %} /// /// Configures {{ setting.description }}. /// /// {{ setting.description | capitalize }}. /// The instance. {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} public {{ provider.name }} Set{{ setting.property_name }}({{ setting.clr_type }} {{ setting.parameter_name }}) { ArgumentNullException.ThrowIfNull({{ setting.parameter_name }}); Registration.Get{{ provider.name }}Settings().{{ setting.property_name }} = {{ setting.parameter_name }}; return this; } {% endcase %} {% endif %} {% endfor %} /// [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals([NotNullWhen(true)] object? obj) => base.Equals(obj); /// [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => base.GetHashCode(); /// [EditorBrowsable(EditorBrowsableState.Never)] public override string? ToString() => base.ToString(); } {% endfor %} } "); var context = CreateTemplateContext(new { Providers = document.Root.Elements("Provider") .Select(static provider => new { Name = (string) provider.Attribute("Name"), DisplayName = (string?) provider.Attribute("DisplayName") ?? (string) provider.Attribute("Name"), Documentation = (string?) provider.Attribute("Documentation"), Obsolete = (bool?) provider.Attribute("Obsolete") ?? false, Environments = provider.Elements("Environment").Select(static environment => new { Name = (string?) environment.Attribute("Name") ?? "Production" }) .ToList(), Settings = provider.Elements("Setting").Select(static setting => new { PropertyName = (string) setting.Attribute("PropertyName"), ParameterName = (string) setting.Attribute("ParameterName"), Collection = (bool?) setting.Attribute("Collection") ?? false, Obsolete = (bool?) setting.Attribute("Obsolete") ?? false, Description = (string) setting.Attribute("Description") is string description ? $"{char.ToLower(description[0], CultureInfo.GetCultureInfo("en-US"))}{description[1..]}" : null, ClrType = (string) setting.Attribute("Type") switch { "Boolean" => "bool", "EncryptionKey" => (string?) setting.Element("EncryptionAlgorithm")?.Attribute("Value") switch { "RS256" or "RS384" or "RS512" => "RsaSecurityKey", _ => "SecurityKey" }, "SigningCertificate" => "X509Certificate2", "SigningKey" => (string?) setting.Element("SigningAlgorithm")?.Attribute("Value") switch { "ES256" or "ES384" or "ES512" => "ECDsaSecurityKey", "PS256" or "PS384" or "PS512" or "RS256" or "RS384" or "RS512" => "RsaSecurityKey", _ => "SecurityKey" }, "String" => "string", "StringHashSet" => "HashSet", "Uri" => "Uri", string value => value } }) .ToList() }) .ToList() }); return template.Render(context); } static string GenerateConstants(FluidParser parser, XDocument document) { var template = parser.Parse(@"#nullable enable namespace OpenIddict.Client.WebIntegration; public static partial class OpenIddictClientWebIntegrationConstants { {% for provider in providers %} public static class {{ provider.name }} { public static class Environments { {% for environment in provider.environments %} public const string {{ environment.name }} = ""{{ environment.name }}""; {% endfor %} } public static class Properties { {% for property in provider.properties %} public const string {{ property.name }} = ""{{ property.dictionary_key }}""; {% endfor %} } {% for group in provider.constants %} public static class {{ group.class }} { {% for constant in group.members %} public const string {{ constant.name }} = ""{{ constant.value }}""; {% endfor %} } {% endfor %} } {% endfor %} public static class Providers { {% for provider in providers %} public const string {{ provider.name }} = ""{{ provider.name }}""; {% endfor %} } public static class ProviderTypes { {% for provider in providers %} public const string {{ provider.name }} = ""{{ provider.id }}""; {% endfor %} } } "); var context = CreateTemplateContext(new { Providers = document.Root.Elements("Provider") .Select(static provider => new { Name = (string) provider.Attribute("Name"), Id = (string) provider.Attribute("Id"), Environments = provider.Elements("Environment").Select(static environment => new { Name = (string?) environment.Attribute("Name") ?? "Production" }) .ToList(), Properties = provider.Elements("Property").Select(static property => new { Name = (string) property.Attribute("Name"), DictionaryKey = (string) property.Attribute("DictionaryKey") }) .ToList(), Constants = provider.Elements("Constant") .Select(static constant => new { Class = (string) constant.Attribute("Class"), Name = (string) constant.Attribute("Name"), Value = (string) constant.Attribute("Value") }) .GroupBy(static constant => constant.Class, StringComparer.Ordinal) .Select(static group => new { Class = group.Key, Members = group.ToList() }) .ToList(), }) .ToList() }); return template.Render(context); } static string GenerateConfigurationClasses(FluidParser parser, XDocument document) { var template = parser.Parse(@"#nullable enable #pragma warning disable CS0618 using System.ComponentModel.DataAnnotations; using System.Text.RegularExpressions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using OpenIddict.Client; using OpenIddict.Extensions; using static OpenIddict.Client.WebIntegration.OpenIddictClientWebIntegrationConstants; using static OpenIddict.Extensions.OpenIddictHelpers; namespace OpenIddict.Client.WebIntegration; public sealed partial class OpenIddictClientWebIntegrationConfiguration { public static partial void ConfigureProvider(OpenIddictClientRegistration registration) { ArgumentNullException.ThrowIfNull(registration); {% for provider in providers %} {% unless forloop.first %}else {% endunless %}if (registration.ProviderType is ProviderTypes.{{ provider.name }}) { if (registration.ProviderSettings is not OpenIddictClientWebIntegrationSettings.{{ provider.name }} settings) { return; } {% for setting in provider.settings %} {% if setting.default_value %} {% case setting.type %} {% when 'String' %} if (string.IsNullOrEmpty(settings.{{ setting.property_name }})) { settings.{{ setting.property_name }} = ""{{ setting.default_value }}""; } {% when 'Uri' %} if (settings.{{ setting.property_name }} is null) { settings.{{ setting.property_name }} = CreateUri(""{{ setting.default_value }}"", UriKind.RelativeOrAbsolute); } {% when 'Boolean' %} if (settings.{{ setting.property_name }} is null) { settings.{{ setting.property_name }} = {{ setting.default_value }}; } {% endcase %} {% endif %} {% if setting.collection %} if (settings.{{ setting.property_name }}.Count is 0) { {% for item in setting.items %} {% if item.default and item.required == false %} settings.{{ setting.property_name }}.Add(""{{ item.value }}""); {% endif %} {% endfor %} } {% endif %} {% for item in setting.items %} {% if item.required %} settings.{{ setting.property_name }}.Add(""{{ item.value }}""); {% endif %} {% endfor %} {% endfor %} {% for environment in provider.environments %} if (settings.Environment is OpenIddictClientWebIntegrationConstants.{{ provider.name }}.Environments.{{ environment.name }}) { if (registration.Scopes.Count is 0) { {% for scope in environment.scopes %} {% if scope.default and scope.required == false %} registration.Scopes.Add(""{{ scope.name }}""); {% endif %} {% endfor %} } {% for scope in environment.scopes %} {% if scope.required %} registration.Scopes.Add(""{{ scope.name }}""); {% endif %} {% endfor %} } {% endfor %} registration.ProviderName ??= Providers.{{ provider.name }}; registration.ProviderDisplayName ??= ""{{ provider.display_name }}""; registration.Issuer ??= settings.Environment switch { {% for environment in provider.environments %} OpenIddictClientWebIntegrationConstants.{{ provider.name }}.Environments.{{ environment.name }} => CreateUri($""{{ environment.issuer | replace: ""'"", '""' }}"", UriKind.Absolute), {% endfor %} _ => null }; registration.ConfigurationEndpoint ??= settings.Environment switch { {% for environment in provider.environments %} OpenIddictClientWebIntegrationConstants.{{ provider.name }}.Environments.{{ environment.name }} {% if environment.configuration_endpoint %} => CreateUri($""{{ environment.configuration_endpoint | replace: ""'"", '""' }}"", UriKind.Absolute), {% else %} => null, {% endif %} {% endfor %} _ => null }; registration.Configuration ??= settings.Environment switch { {% for environment in provider.environments %} {% if environment.configuration %} OpenIddictClientWebIntegrationConstants.{{ provider.name }}.Environments.{{ environment.name }} => new OpenIddictConfiguration { {% if environment.configuration.authorization_endpoint %} AuthorizationEndpoint = CreateUri($""{{ environment.configuration.authorization_endpoint | replace: ""'"", '""' }}"", UriKind.Absolute), {% endif %} {% if environment.configuration.device_authorization_endpoint %} DeviceAuthorizationEndpoint = CreateUri($""{{ environment.configuration.device_authorization_endpoint | replace: ""'"", '""' }}"", UriKind.Absolute), {% endif %} {% if environment.configuration.introspection_endpoint %} IntrospectionEndpoint = CreateUri($""{{ environment.configuration.introspection_endpoint | replace: ""'"", '""' }}"", UriKind.Absolute), {% endif %} {% if environment.configuration.revocation_endpoint %} RevocationEndpoint = CreateUri($""{{ environment.configuration.revocation_endpoint | replace: ""'"", '""' }}"", UriKind.Absolute), {% endif %} {% if environment.configuration.token_endpoint %} TokenEndpoint = CreateUri($""{{ environment.configuration.token_endpoint | replace: ""'"", '""' }}"", UriKind.Absolute), {% endif %} {% if environment.configuration.user_info_endpoint %} UserInfoEndpoint = CreateUri($""{{ environment.configuration.user_info_endpoint | replace: ""'"", '""' }}"", UriKind.Absolute), {% endif %} AuthorizationResponseIssParameterSupported = {{ environment.configuration.authorization_response_iss_parameter_supported | default: ""null"" }}, CodeChallengeMethodsSupported = { {% for method in environment.configuration.code_challenge_methods_supported %} ""{{ method }}"", {% endfor %} }, GrantTypesSupported = { {% for type in environment.configuration.grant_types_supported %} ""{{ type }}"", {% endfor %} }, ResponseModesSupported = { {% for mode in environment.configuration.response_modes_supported %} ""{{ mode }}"", {% endfor %} }, ResponseTypesSupported = { {% for type in environment.configuration.response_types_supported %} ""{{ type }}"", {% endfor %} }, ScopesSupported = { {% for scope in environment.configuration.scopes_supported %} ""{{ scope }}"", {% endfor %} }, DeviceAuthorizationEndpointAuthMethodsSupported = { {% for method in environment.configuration.device_authorization_endpoint_auth_methods_supported %} ""{{ method }}"", {% endfor %} }, IntrospectionEndpointAuthMethodsSupported = { {% for method in environment.configuration.introspection_endpoint_auth_methods_supported %} ""{{ method }}"", {% endfor %} }, RevocationEndpointAuthMethodsSupported = { {% for method in environment.configuration.revocation_endpoint_auth_methods_supported %} ""{{ method }}"", {% endfor %} }, TokenEndpointAuthMethodsSupported = { {% for method in environment.configuration.token_endpoint_auth_methods_supported %} ""{{ method }}"", {% endfor %} } }, {% else %} OpenIddictClientWebIntegrationConstants.{{ provider.name }}.Environments.{{ environment.name }} => null, {% endif %} {% endfor %} _ => null }; {% for setting in provider.settings %} {% if setting.type == 'EncryptionKey' %} if (settings.{{ setting.property_name }} is not null) { registration.EncryptionCredentials.Add(new EncryptingCredentials(settings.{{ setting.property_name }}, ""{{ setting.encryption_algorithm }}"", SecurityAlgorithms.Aes256CbcHmacSha512)); } {% endif %} {% endfor %} {% for setting in provider.settings %} {% if setting.type == 'SigningCertificate' %} if (settings.{{ setting.property_name }} is not null) { var key = new X509SecurityKey(settings.{{ setting.property_name }}); if (key.IsSupportedAlgorithm(SecurityAlgorithms.RsaSha256)) { registration.SigningCredentials.Add(new SigningCredentials(key, SecurityAlgorithms.RsaSha256)); } else if (key.IsSupportedAlgorithm(SecurityAlgorithms.HmacSha256)) { registration.SigningCredentials.Add(new SigningCredentials(key, SecurityAlgorithms.HmacSha256)); } // Note: ECDSA algorithms are bound to specific curves and must be treated separately. else if (key.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha256)) { registration.SigningCredentials.Add(new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256)); } else if (key.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha384)) { registration.SigningCredentials.Add(new SigningCredentials(key, SecurityAlgorithms.EcdsaSha384)); } else if (key.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha512)) { registration.SigningCredentials.Add(new SigningCredentials(key, SecurityAlgorithms.EcdsaSha512)); } } {% endif %} {% if setting.type == 'SigningKey' %} if (settings.{{ setting.property_name }} is not null and not AsymmetricSecurityKey { PrivateKeyStatus: PrivateKeyStatus.DoesNotExist }) { {% if setting.signing_algorithm %} registration.SigningCredentials.Add(new SigningCredentials(settings.{{ setting.property_name }}, ""{{ setting.signing_algorithm }}"")); {% else %} if (settings.{{ setting.property_name }}.IsSupportedAlgorithm(SecurityAlgorithms.RsaSha256)) { registration.SigningCredentials.Add(new SigningCredentials(settings.{{ setting.property_name }}, SecurityAlgorithms.RsaSha256)); } else if (settings.{{ setting.property_name }}.IsSupportedAlgorithm(SecurityAlgorithms.HmacSha256)) { registration.SigningCredentials.Add(new SigningCredentials(settings.{{ setting.property_name }}, SecurityAlgorithms.HmacSha256)); } // Note: ECDSA algorithms are bound to specific curves and must be treated separately. else if (settings.{{ setting.property_name }}.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha256)) { registration.SigningCredentials.Add(new SigningCredentials(settings.{{ setting.property_name }}, SecurityAlgorithms.EcdsaSha256)); } else if (settings.{{ setting.property_name }}.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha384)) { registration.SigningCredentials.Add(new SigningCredentials(settings.{{ setting.property_name }}, SecurityAlgorithms.EcdsaSha384)); } else if (settings.{{ setting.property_name }}.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha512)) { registration.SigningCredentials.Add(new SigningCredentials(settings.{{ setting.property_name }}, SecurityAlgorithms.EcdsaSha512)); } {% endif %} } {% endif %} {% endfor %} } {% endfor %} static Uri? CreateUri(string? value, UriKind kind) => Uri.TryCreate(value, kind, out Uri? uri) ? uri : null; } public static partial IEnumerable ValidateProvider(OpenIddictClientRegistration registration) { ArgumentNullException.ThrowIfNull(registration); return Execute(); IEnumerable Execute() { {% for provider in providers %} {% unless forloop.first %}else {% endunless %}if (registration.ProviderType is ProviderTypes.{{ provider.name }}) { if (registration.ProviderSettings is not OpenIddictClientWebIntegrationSettings.{{ provider.name }} settings) { yield return new ValidationResult(SR.GetResourceString(SR.ID0406)); // Note: if the settings instance is missing or of the wrong type, abort any further validation. yield break; } // Ensure the specified environment is valid. if (settings.Environment is not ( {% for environment in provider.environments %} OpenIddictClientWebIntegrationConstants.{{ provider.name }}.Environments.{{ environment.name }}{% unless forloop.last %} or{% endunless %} {% endfor %} )) { yield return new ValidationResult(SR.FormatID0194(nameof(settings.Environment))); } {% for setting in provider.settings %} {% if setting.required %} {% if setting.type == 'String' %} if (string.IsNullOrEmpty(settings.{{ setting.property_name }})) {% else %} if (settings.{{ setting.property_name }} is null) {% endif %} { yield return new ValidationResult(SR.FormatID0332(nameof(settings.{{ setting.property_name }}), Providers.{{ provider.name }})); } {% endif %} {% if setting.type == 'Uri' %} else if (!settings.{{ setting.property_name }}.IsAbsoluteUri || OpenIddictHelpers.IsImplicitFileUri(settings.{{ setting.property_name }})) { yield return new ValidationResult(SR.FormatID0350(nameof(settings.{{ setting.property_name }}), Providers.{{ provider.name }})); } {% endif %} {% endfor %} {% for setting in provider.settings %} {% if setting.type == 'SigningCertificate' %} if (settings.{{ setting.property_name }} is not null) { var key = new X509SecurityKey(settings.{{ setting.property_name }}); if (!key.IsSupportedAlgorithm(SecurityAlgorithms.RsaSha256) && !key.IsSupportedAlgorithm(SecurityAlgorithms.HmacSha256) && !key.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha256) && !key.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha384) && !key.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha512)) { yield return new ValidationResult(SR.GetResourceString(SR.ID0068)); } } {% endif %} {% if setting.type == 'SigningKey' %} if (settings.{{ setting.property_name }} is not null) { // If the signing key is an asymmetric security key, ensure it has a private key. if (settings.{{ setting.property_name }} is AsymmetricSecurityKey { PrivateKeyStatus: PrivateKeyStatus.DoesNotExist }) { yield return new ValidationResult(SR.GetResourceString(SR.ID0067)); } {% unless setting.signing_algorithm %} if (!settings.{{ setting.property_name }}.IsSupportedAlgorithm(SecurityAlgorithms.RsaSha256) && !settings.{{ setting.property_name }}.IsSupportedAlgorithm(SecurityAlgorithms.HmacSha256) && !settings.{{ setting.property_name }}.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha256) && !settings.{{ setting.property_name }}.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha384) && !settings.{{ setting.property_name }}.IsSupportedAlgorithm(SecurityAlgorithms.EcdsaSha512)) { yield return new ValidationResult(SR.GetResourceString(SR.ID0068)); } {% endunless %} } {% endif %} {% endfor %} } {% endfor %} else { yield return new ValidationResult(SR.GetResourceString(SR.ID0407)); } } } } "); var context = CreateTemplateContext(new { Providers = document.Root.Elements("Provider") .Select(static provider => new { Name = (string) provider.Attribute("Name"), DisplayName = (string?) provider.Attribute("DisplayName") ?? (string) provider.Attribute("Name"), Environments = provider.Elements("Environment").Select(static environment => new { Name = (string?) environment.Attribute("Name") ?? "Production", Issuer = (string) environment.Attribute("Issuer"), ConfigurationEndpoint = (string?) environment.Attribute("ConfigurationEndpoint"), Configuration = environment.Element("Configuration") switch { XElement configuration => new { AuthorizationEndpoint = (string?) configuration.Attribute("AuthorizationEndpoint"), DeviceAuthorizationEndpoint = (string?) configuration.Attribute("DeviceAuthorizationEndpoint"), IntrospectionEndpoint = (string?) configuration.Attribute("IntrospectionEndpoint"), RevocationEndpoint = (string?) configuration.Attribute("RevocationEndpoint"), TokenEndpoint = (string?) configuration.Attribute("TokenEndpoint"), UserInfoEndpoint = (string?) configuration.Attribute("UserInfoEndpoint"), AuthorizationResponseIssParameterSupported = (bool?) configuration.Attribute("AuthorizationResponseIssParameterSupported"), CodeChallengeMethodsSupported = configuration.Elements("CodeChallengeMethod").ToList() switch { { Count: > 0 } methods => methods.Select(static type => (string?) type.Attribute("Value")).ToList(), _ => [] }, GrantTypesSupported = configuration.Elements("GrantType").ToList() switch { { Count: > 0 } types => types.Select(static type => (string?) type.Attribute("Value")).ToList(), // If no explicit grant type was set, assume the provider only supports the code flow. _ => ["authorization_code"] }, ResponseModesSupported = configuration.Elements("ResponseMode").ToList() switch { { Count: > 0 } modes => modes.Select(static type => (string?) type.Attribute("Value")).ToList(), // If no explicit response mode was set, assume the provider only supports the query response mode. _ => ["query"] }, ResponseTypesSupported = configuration.Elements("ResponseType").ToList() switch { { Count: > 0 } types => types.Select(static type => (string?) type.Attribute("Value")).ToList(), // If no explicit response type was set, assume the provider only supports the code flow. _ => ["code"] }, ScopesSupported = configuration.Elements("Scope").ToList() switch { { Count: > 0 } types => types.Select(static type => (string?) type.Attribute("Value")).ToList(), _ => [] }, DeviceAuthorizationEndpointAuthMethodsSupported = configuration.Elements("DeviceAuthorizationEndpointAuthMethod").ToList() switch { { Count: > 0 } methods => methods.Select(static type => (string?) type.Attribute("Value")).ToList(), // If no explicit client authentication method was set, assume the provider only supports // flowing the client credentials as part of the device authorization request payload. _ => ["client_secret_post"] }, IntrospectionEndpointAuthMethodsSupported = configuration.Elements("IntrospectionEndpointAuthMethod").ToList() switch { { Count: > 0 } methods => methods.Select(static type => (string?) type.Attribute("Value")).ToList(), // If no explicit client authentication method was set, assume the provider only // supports flowing the client credentials as part of the introspection request payload. _ => ["client_secret_post"] }, RevocationEndpointAuthMethodsSupported = configuration.Elements("RevocationEndpointAuthMethod").ToList() switch { { Count: > 0 } methods => methods.Select(static type => (string?) type.Attribute("Value")).ToList(), // If no explicit client authentication method was set, assume the provider only // supports flowing the client credentials as part of the revocation request payload. _ => ["client_secret_post"] }, TokenEndpointAuthMethodsSupported = configuration.Elements("TokenEndpointAuthMethod").ToList() switch { { Count: > 0 } methods => methods.Select(static type => (string?) type.Attribute("Value")).ToList(), // If no explicit client authentication method was set, assume the provider only // supports flowing the client credentials as part of the token request payload. _ => ["client_secret_post"] } }, _ => null }, Scopes = environment.Elements("Scope").Select(static setting => new { Name = (string) setting.Attribute("Name"), Default = (bool?) setting.Attribute("Default") ?? false, Required = (bool?) setting.Attribute("Required") ?? false }) }) .ToList(), Settings = provider.Elements("Setting").Select(static setting => new { PropertyName = (string) setting.Attribute("PropertyName"), Type = (string) setting.Attribute("Type"), Required = (bool?) setting.Attribute("Required") ?? false, Collection = (bool?) setting.Attribute("Collection") ?? false, EncryptionAlgorithm = (string?) setting.Element("EncryptionAlgorithm")?.Attribute("Value"), SigningAlgorithm = (string?) setting.Element("SigningAlgorithm")?.Attribute("Value"), DefaultValue = (string?) setting.Attribute("DefaultValue"), Items = setting.Elements("Item").Select(static item => new { Value = (string) item.Attribute("Value"), Default = (bool?) item.Attribute("Default") ?? false, Required = (bool?) item.Attribute("Required") ?? false }) .ToList() }) .ToList() }) .ToList() }); return template.Render(context); } static string GenerateHelpers(FluidParser parser, XDocument document) { var template = parser.Parse(@"#nullable enable using Microsoft.IdentityModel.Tokens; using OpenIddict.Client; using OpenIddict.Client.WebIntegration; using static OpenIddict.Client.WebIntegration.OpenIddictClientWebIntegrationConstants; namespace OpenIddict.Client.WebIntegration; public static partial class OpenIddictClientWebIntegrationHelpers { {% for provider in providers %} /// /// Resolves the {{ provider.display_name }} provider settings from the specified registration. /// /// The client registration. /// The {{ provider.display_name }} provider settings. /// The provider options cannot be resolved. public static OpenIddictClientWebIntegrationSettings.{{ provider.name }} Get{{ provider.name }}Settings(this OpenIddictClientRegistration registration) { ArgumentNullException.ThrowIfNull(registration); return registration.ProviderSettings is OpenIddictClientWebIntegrationSettings.{{ provider.name }} settings ? settings : throw new InvalidOperationException(SR.FormatID0333(Providers.{{ provider.name }})); } {% endfor %} } "); var context = CreateTemplateContext(new { Providers = document.Root.Elements("Provider") .Select(static provider => new { Name = (string) provider.Attribute("Name"), DisplayName = (string?) provider.Attribute("DisplayName") ?? (string) provider.Attribute("Name") }) .ToList() }); return template.Render(context); } static string GenerateSettings(FluidParser parser, XDocument document) { var template = parser.Parse(@"#nullable enable using System.Security.Cryptography.X509Certificates; using Microsoft.IdentityModel.Tokens; namespace OpenIddict.Client.WebIntegration; public sealed partial class OpenIddictClientWebIntegrationSettings { {% for provider in providers %} /// /// Provides various options needed to configure the {{ provider.display_name }} integration. /// public sealed class {{ provider.name }} { /// /// Gets or sets the environment that determines the endpoints to use (by default, ""Production""). /// public string? Environment { get; set; } = OpenIddictClientWebIntegrationConstants.{{ provider.name }}.Environments.Production; {% for setting in provider.settings %} /// /// Gets or sets {{ setting.description }}. /// {% if setting.obsolete -%} [Obsolete(""This option is no longer supported and will be removed in a future version."")] {% endif -%} {% if setting.collection %} public HashSet<{{ setting.clr_type }}> {{ setting.property_name }} { get; } = new(); {% else %} public {{ setting.clr_type }}? {{ setting.property_name }} { get; set; } {% endif %} {% endfor %} } {% endfor %} } "); var context = CreateTemplateContext(new { Providers = document.Root.Elements("Provider") .Select(static provider => new { Name = (string) provider.Attribute("Name"), DisplayName = (string?) provider.Attribute("DisplayName") ?? (string) provider.Attribute("Name"), Settings = provider.Elements("Setting").Select(static setting => new { PropertyName = (string) setting.Attribute("PropertyName"), Collection = (bool?) setting.Attribute("Collection") ?? false, Obsolete = (bool?) setting.Attribute("Obsolete") ?? false, Description = (string) setting.Attribute("Description") is string description ? $"{char.ToLower(description[0], CultureInfo.GetCultureInfo("en-US"))}{description[1..]}" : null, ClrType = (string) setting.Attribute("Type") switch { "Boolean" => "bool", "EncryptionKey" => (string?) setting.Element("EncryptionAlgorithm")?.Attribute("Value") switch { "RS256" or "RS384" or "RS512" => "RsaSecurityKey", _ => "SecurityKey" }, "SigningCertificate" => "X509Certificate2", "SigningKey" => (string?) setting.Element("SigningAlgorithm")?.Attribute("Value") switch { "ES256" or "ES384" or "ES512" => "ECDsaSecurityKey", "PS256" or "PS384" or "PS512" or "RS256" or "RS384" or "RS512" => "RsaSecurityKey", _ => "SecurityKey" }, "String" => "string", "StringHashSet" => "HashSet", "Uri" => "Uri", string value => value } }) .ToList() }) .ToList() }); return template.Render(context); } static TemplateContext CreateTemplateContext(object model) => new(model, new TemplateOptions { ModelNamesComparer = StringComparers.SnakeCase }); } }