| | | 1 | | |
| | | 2 | | using Kestrun.Claims; |
| | | 3 | | using Kestrun.Hosting; |
| | | 4 | | using Microsoft.AspNetCore.Authentication; |
| | | 5 | | using Microsoft.AspNetCore.Authentication.Cookies; |
| | | 6 | | using Microsoft.AspNetCore.Authentication.OAuth; |
| | | 7 | | using System.Text.Json; |
| | | 8 | | |
| | | 9 | | namespace Kestrun.Authentication; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Options for OAuth2 authentication. |
| | | 13 | | /// </summary> |
| | | 14 | | public class OAuth2Options : OAuthOptions, IOpenApiAuthenticationOptions, IAuthenticationHostOptions, IOAuthCommonOption |
| | | 15 | | { |
| | | 16 | | /// <summary> |
| | | 17 | | /// Options for cookie authentication. |
| | | 18 | | /// </summary> |
| | 19 | 19 | | public CookieAuthOptions CookieOptions { get; } |
| | | 20 | | |
| | | 21 | | /// <inheritdoc/> |
| | 9 | 22 | | public bool GlobalScheme { get; set; } |
| | | 23 | | |
| | | 24 | | /// <inheritdoc/> |
| | 9 | 25 | | public string? Description { get; set; } |
| | | 26 | | |
| | | 27 | | /// <inheritdoc/> |
| | 2 | 28 | | public string? DisplayName { get; set; } |
| | | 29 | | |
| | | 30 | | /// <inheritdoc/> |
| | 9 | 31 | | public bool Deprecated { get; set; } |
| | | 32 | | |
| | | 33 | | /// <inheritdoc/> |
| | 56 | 34 | | public string[] DocumentationId { get; set; } = []; |
| | | 35 | | |
| | | 36 | | #pragma warning disable IDE0370 // Remove unnecessary suppression |
| | | 37 | | /// <inheritdoc/> |
| | 14 | 38 | | public KestrunHost Host { get; set; } = default!; |
| | | 39 | | #pragma warning restore IDE0370 // Remove unnecessary suppression |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Initializes a new instance of the <see cref="OAuth2Options"/> class. |
| | | 43 | | /// </summary> |
| | 30 | 44 | | public OAuth2Options() |
| | | 45 | | { |
| | 30 | 46 | | CookieOptions = new CookieAuthOptions() |
| | 30 | 47 | | { |
| | 30 | 48 | | SlidingExpiration = true |
| | 30 | 49 | | }; |
| | 30 | 50 | | } |
| | | 51 | | /// <summary> |
| | | 52 | | /// Gets or sets the authentication scheme name. |
| | | 53 | | /// </summary> |
| | 55 | 54 | | public string AuthenticationScheme { get; set; } = AuthenticationDefaults.OAuth2SchemeName; |
| | | 55 | | |
| | | 56 | | /// <summary> |
| | | 57 | | /// Gets the cookie authentication scheme name. |
| | | 58 | | /// </summary> |
| | | 59 | | public string CookieScheme => |
| | 14 | 60 | | CookieOptions.Cookie.Name ?? (CookieAuthenticationDefaults.AuthenticationScheme + "." + AuthenticationScheme); |
| | | 61 | | |
| | | 62 | | /// <summary> |
| | | 63 | | /// Configuration for claim policy enforcement. |
| | | 64 | | /// </summary> |
| | 35 | 65 | | public ClaimPolicyConfig? ClaimPolicy { get; set; } |
| | | 66 | | |
| | | 67 | | /// <summary> |
| | | 68 | | /// Gets or sets the OAuth2 authorization server metadata URL (RFC 8414). |
| | | 69 | | /// This is used for OpenAPI metadata and optional endpoint discovery. |
| | | 70 | | /// </summary> |
| | 62 | 71 | | public string? OAuth2MetadataUrl { get; set; } |
| | | 72 | | |
| | | 73 | | /// <summary> |
| | | 74 | | /// Gets or sets a value indicating whether missing OAuth2 endpoints should be |
| | | 75 | | /// resolved from <see cref="OAuth2MetadataUrl"/>. |
| | | 76 | | /// </summary> |
| | 23 | 77 | | public bool ResolveEndpointsFromMetadata { get; set; } = false; |
| | | 78 | | |
| | | 79 | | /// <summary> |
| | | 80 | | /// Gets or sets a value indicating whether OAuth2 metadata discovery may use a non-HTTPS URL. |
| | | 81 | | /// Defaults to <see langword="false"/> so metadata discovery requires HTTPS. |
| | | 82 | | /// </summary> |
| | 10 | 83 | | public bool AllowInsecureMetadataHttp { get; set; } = false; |
| | | 84 | | |
| | | 85 | | private Serilog.ILogger? _logger; |
| | | 86 | | /// <inheritdoc/> |
| | | 87 | | public Serilog.ILogger Logger |
| | | 88 | | { |
| | 0 | 89 | | get => _logger ?? (Host is null ? Serilog.Log.Logger : Host.Logger); set => _logger = value; |
| | | 90 | | } |
| | | 91 | | |
| | | 92 | | /// <summary> |
| | | 93 | | /// Helper to copy values from a user-supplied OAuth2Options instance to the instance |
| | | 94 | | /// created by the framework inside AddOAuth(). Reassigning the local variable (opts = source) would |
| | | 95 | | /// not work because only the local reference changes – the framework keeps the original instance. |
| | | 96 | | /// </summary> |
| | | 97 | | /// <param name="target">The target OAuth2Options instance to copy values to.</param> |
| | | 98 | | public void ApplyTo(OAuth2Options target) |
| | | 99 | | { |
| | 2 | 100 | | ApplyTo((OAuthOptions)target); |
| | 1 | 101 | | CookieOptions.ApplyTo(target.CookieOptions); |
| | | 102 | | // OpenAPI / documentation properties |
| | 1 | 103 | | target.GlobalScheme = GlobalScheme; |
| | 1 | 104 | | target.Description = Description; |
| | 1 | 105 | | target.DisplayName = DisplayName; |
| | 1 | 106 | | target.DocumentationId = DocumentationId; |
| | 1 | 107 | | target.Host = Host; |
| | 1 | 108 | | target.ClaimPolicy = ClaimPolicy; |
| | 1 | 109 | | target.Deprecated = Deprecated; |
| | 1 | 110 | | target.OAuth2MetadataUrl = OAuth2MetadataUrl; |
| | 1 | 111 | | target.ResolveEndpointsFromMetadata = ResolveEndpointsFromMetadata; |
| | 1 | 112 | | target.AllowInsecureMetadataHttp = AllowInsecureMetadataHttp; |
| | 1 | 113 | | } |
| | | 114 | | |
| | | 115 | | /// <summary> |
| | | 116 | | /// Apply these options to the target <see cref="OAuthOptions"/> instance. |
| | | 117 | | /// </summary> |
| | | 118 | | /// <param name="target">The target OAuthOptions instance to apply settings to.</param> |
| | | 119 | | public void ApplyTo(OAuthOptions target) |
| | | 120 | | { |
| | | 121 | | // Core OAuth endpoints |
| | 7 | 122 | | target.AuthorizationEndpoint = AuthorizationEndpoint; |
| | 6 | 123 | | target.TokenEndpoint = TokenEndpoint; |
| | 6 | 124 | | target.UserInformationEndpoint = UserInformationEndpoint; |
| | 6 | 125 | | target.ClientId = ClientId; |
| | 6 | 126 | | target.ClientSecret = ClientSecret; |
| | 6 | 127 | | target.CallbackPath = CallbackPath; |
| | | 128 | | |
| | | 129 | | // OAuth configuration |
| | 6 | 130 | | target.UsePkce = UsePkce; |
| | 6 | 131 | | target.SaveTokens = SaveTokens; |
| | 6 | 132 | | target.ClaimsIssuer = ClaimsIssuer; |
| | | 133 | | |
| | | 134 | | // Scopes - clear and copy |
| | 6 | 135 | | target.Scope.Clear(); |
| | 16 | 136 | | foreach (var scope in Scope) |
| | | 137 | | { |
| | 2 | 138 | | target.Scope.Add(scope); |
| | | 139 | | } |
| | | 140 | | |
| | | 141 | | // Token handling |
| | 6 | 142 | | target.AccessDeniedPath = AccessDeniedPath; |
| | 6 | 143 | | target.RemoteAuthenticationTimeout = RemoteAuthenticationTimeout; |
| | 6 | 144 | | target.ReturnUrlParameter = ReturnUrlParameter; |
| | | 145 | | |
| | | 146 | | // Scheme linkage |
| | 6 | 147 | | target.SignInScheme = SignInScheme; |
| | | 148 | | |
| | | 149 | | // Backchannel configuration |
| | 6 | 150 | | if (Backchannel != null) |
| | | 151 | | { |
| | 0 | 152 | | target.Backchannel = Backchannel; |
| | | 153 | | } |
| | 6 | 154 | | if (BackchannelHttpHandler != null) |
| | | 155 | | { |
| | 0 | 156 | | target.BackchannelHttpHandler = BackchannelHttpHandler; |
| | | 157 | | } |
| | 6 | 158 | | if (BackchannelTimeout != default) |
| | | 159 | | { |
| | 6 | 160 | | target.BackchannelTimeout = BackchannelTimeout; |
| | | 161 | | } |
| | | 162 | | |
| | | 163 | | // Claim actions |
| | 6 | 164 | | if (ClaimActions != null) |
| | | 165 | | { |
| | 16 | 166 | | foreach (var jka in ClaimActions |
| | 6 | 167 | | .OfType<Microsoft.AspNetCore.Authentication.OAuth.Claims.JsonKeyClaimAction>() |
| | 8 | 168 | | .Where(a => !string.IsNullOrEmpty(a.JsonKey) && !string.IsNullOrEmpty(a.ClaimType))) |
| | | 169 | | { |
| | 2 | 170 | | target.ClaimActions.MapJsonKey(jka.ClaimType, jka.JsonKey); |
| | | 171 | | } |
| | | 172 | | } |
| | | 173 | | |
| | | 174 | | // Events - copy if provided |
| | 6 | 175 | | if (Events != null) |
| | | 176 | | { |
| | 6 | 177 | | target.Events = Events; |
| | | 178 | | } |
| | 6 | 179 | | if (EventsType != null) |
| | | 180 | | { |
| | 0 | 181 | | target.EventsType = EventsType; |
| | | 182 | | } |
| | | 183 | | |
| | | 184 | | // Other properties |
| | 6 | 185 | | target.StateDataFormat = StateDataFormat; |
| | 6 | 186 | | } |
| | | 187 | | |
| | | 188 | | /// <summary> |
| | | 189 | | /// Populates missing OAuth2 endpoints from an OAuth2 metadata document. |
| | | 190 | | /// </summary> |
| | | 191 | | /// <param name="options">The OAuth2 options to populate.</param> |
| | | 192 | | /// <param name="httpClient">The HTTP client used to fetch metadata.</param> |
| | | 193 | | /// <param name="cancellationToken">A cancellation token.</param> |
| | | 194 | | /// <returns>A task that represents the asynchronous operation.</returns> |
| | | 195 | | internal static async Task PopulateEndpointsFromMetadataAsync( |
| | | 196 | | OAuth2Options options, |
| | | 197 | | HttpClient httpClient, |
| | | 198 | | CancellationToken cancellationToken = default) |
| | | 199 | | { |
| | 9 | 200 | | ArgumentNullException.ThrowIfNull(options); |
| | 9 | 201 | | ArgumentNullException.ThrowIfNull(httpClient); |
| | | 202 | | |
| | 9 | 203 | | if (string.IsNullOrWhiteSpace(options.OAuth2MetadataUrl)) |
| | | 204 | | { |
| | 1 | 205 | | return; |
| | | 206 | | } |
| | | 207 | | |
| | 8 | 208 | | if (!HasMissingMetadataEndpoints(options)) |
| | | 209 | | { |
| | 1 | 210 | | return; |
| | | 211 | | } |
| | | 212 | | |
| | 7 | 213 | | using var json = await FetchMetadataDocumentAsync( |
| | 7 | 214 | | options.OAuth2MetadataUrl, |
| | 7 | 215 | | httpClient, |
| | 7 | 216 | | cancellationToken).ConfigureAwait(false); |
| | | 217 | | |
| | 5 | 218 | | if (TryResolveEndpointFromMetadata( |
| | 5 | 219 | | options.AuthorizationEndpoint, |
| | 5 | 220 | | json.RootElement, |
| | 5 | 221 | | "authorization_endpoint", |
| | 5 | 222 | | out var authorizationEndpoint)) |
| | | 223 | | { |
| | 4 | 224 | | options.AuthorizationEndpoint = authorizationEndpoint; |
| | | 225 | | } |
| | | 226 | | |
| | 5 | 227 | | if (TryResolveEndpointFromMetadata( |
| | 5 | 228 | | options.TokenEndpoint, |
| | 5 | 229 | | json.RootElement, |
| | 5 | 230 | | "token_endpoint", |
| | 5 | 231 | | out var tokenEndpoint)) |
| | | 232 | | { |
| | 4 | 233 | | options.TokenEndpoint = tokenEndpoint; |
| | | 234 | | } |
| | | 235 | | |
| | 5 | 236 | | if (TryResolveEndpointFromMetadata( |
| | 5 | 237 | | options.UserInformationEndpoint, |
| | 5 | 238 | | json.RootElement, |
| | 5 | 239 | | "userinfo_endpoint", |
| | 5 | 240 | | out var userInformationEndpoint)) |
| | | 241 | | { |
| | 5 | 242 | | options.UserInformationEndpoint = userInformationEndpoint; |
| | | 243 | | } |
| | 7 | 244 | | } |
| | | 245 | | |
| | | 246 | | /// <summary> |
| | | 247 | | /// Determines whether any OAuth2 endpoint that can be resolved from metadata is missing. |
| | | 248 | | /// </summary> |
| | | 249 | | /// <param name="options">The OAuth2 options to inspect.</param> |
| | | 250 | | /// <returns><see langword="true"/> when at least one endpoint is missing; otherwise, <see langword="false"/>.</retu |
| | | 251 | | private static bool HasMissingMetadataEndpoints(OAuth2Options options) => |
| | 8 | 252 | | string.IsNullOrWhiteSpace(options.AuthorizationEndpoint) || |
| | 8 | 253 | | string.IsNullOrWhiteSpace(options.TokenEndpoint) || |
| | 8 | 254 | | string.IsNullOrWhiteSpace(options.UserInformationEndpoint); |
| | | 255 | | |
| | | 256 | | /// <summary> |
| | | 257 | | /// Downloads and parses the OAuth2 metadata document. |
| | | 258 | | /// </summary> |
| | | 259 | | /// <param name="metadataUrl">The metadata document URL.</param> |
| | | 260 | | /// <param name="httpClient">The HTTP client used to fetch metadata.</param> |
| | | 261 | | /// <param name="cancellationToken">A cancellation token.</param> |
| | | 262 | | /// <returns>The parsed metadata document.</returns> |
| | | 263 | | private static async Task<JsonDocument> FetchMetadataDocumentAsync( |
| | | 264 | | string metadataUrl, |
| | | 265 | | HttpClient httpClient, |
| | | 266 | | CancellationToken cancellationToken) |
| | | 267 | | { |
| | 7 | 268 | | using var response = await httpClient.GetAsync(metadataUrl, cancellationToken).ConfigureAwait(false); |
| | 7 | 269 | | _ = response.EnsureSuccessStatusCode(); |
| | | 270 | | |
| | 5 | 271 | | await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); |
| | 5 | 272 | | return await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); |
| | 5 | 273 | | } |
| | | 274 | | |
| | | 275 | | /// <summary> |
| | | 276 | | /// Resolves a single OAuth2 endpoint value from metadata when the current value is missing. |
| | | 277 | | /// </summary> |
| | | 278 | | /// <param name="currentEndpoint">The current endpoint value.</param> |
| | | 279 | | /// <param name="metadataRoot">The metadata JSON root element.</param> |
| | | 280 | | /// <param name="propertyName">The metadata property name to read.</param> |
| | | 281 | | /// <param name="resolvedEndpoint">The resolved endpoint, when available.</param> |
| | | 282 | | /// <returns><see langword="true"/> when an endpoint was resolved from metadata; otherwise <see langword="false"/>.< |
| | | 283 | | /// <exception cref="FormatException">Thrown when a discovered endpoint is not an absolute URI.</exception> |
| | | 284 | | private static bool TryResolveEndpointFromMetadata( |
| | | 285 | | string? currentEndpoint, |
| | | 286 | | JsonElement metadataRoot, |
| | | 287 | | string propertyName, |
| | | 288 | | out string resolvedEndpoint) |
| | | 289 | | { |
| | 15 | 290 | | resolvedEndpoint = string.Empty; |
| | | 291 | | |
| | 15 | 292 | | if (!string.IsNullOrWhiteSpace(currentEndpoint)) |
| | | 293 | | { |
| | 2 | 294 | | return false; |
| | | 295 | | } |
| | | 296 | | |
| | 13 | 297 | | if (!metadataRoot.TryGetProperty(propertyName, out var endpointElement) || |
| | 13 | 298 | | endpointElement.ValueKind != JsonValueKind.String) |
| | | 299 | | { |
| | 0 | 300 | | return false; |
| | | 301 | | } |
| | | 302 | | |
| | 13 | 303 | | var endpoint = endpointElement.GetString(); |
| | 13 | 304 | | if (string.IsNullOrWhiteSpace(endpoint)) |
| | | 305 | | { |
| | 0 | 306 | | return false; |
| | | 307 | | } |
| | | 308 | | |
| | 13 | 309 | | if (Uri.TryCreate(endpoint, UriKind.Absolute, out _)) |
| | | 310 | | { |
| | 13 | 311 | | resolvedEndpoint = endpoint; |
| | 13 | 312 | | return true; |
| | | 313 | | } |
| | | 314 | | |
| | 0 | 315 | | throw new FormatException($"OAuth2 metadata property '{propertyName}' must be an absolute URI, but received '{en |
| | | 316 | | } |
| | | 317 | | } |