|
| 1 | +// Parts of this code file are based on the JwtBearerHandler class in the Microsoft.AspNetCore.Authentication.JwtBearer package found at: |
| 2 | +// https://github.com/dotnet/aspnetcore/blob/5493b413d1df3aaf00651bdf1cbd8135fa63f517/src/Security/Authentication/JwtBearer/src/JwtBearerHandler.cs |
| 3 | +// |
| 4 | +// Those sections of code may be subject to the MIT license found at: |
| 5 | +// https://github.com/dotnet/aspnetcore/blob/5493b413d1df3aaf00651bdf1cbd8135fa63f517/LICENSE.txt |
| 6 | + |
| 7 | +using System.Security.Claims; |
| 8 | +using GraphQL.AspNetCore3.WebSockets; |
| 9 | +using Microsoft.AspNetCore.Authentication; |
| 10 | +using Microsoft.AspNetCore.Authentication.JwtBearer; |
| 11 | +using Microsoft.AspNetCore.Http; |
| 12 | +using Microsoft.Extensions.DependencyInjection; |
| 13 | +using Microsoft.Extensions.Options; |
| 14 | +using Microsoft.IdentityModel.Tokens; |
| 15 | + |
| 16 | +namespace GraphQL.AspNetCore3.JwtBearer; |
| 17 | + |
| 18 | +/// <summary> |
| 19 | +/// Authenticates WebSocket connections via the 'payload' of the initialization packet. |
| 20 | +/// This is necessary because WebSocket connections initiated from the browser cannot |
| 21 | +/// authenticate via HTTP headers. |
| 22 | +/// <br/><br/> |
| 23 | +/// Notes: |
| 24 | +/// <list type="bullet"> |
| 25 | +/// <item>This class is not used when authenticating over GET/POST.</item> |
| 26 | +/// <item> |
| 27 | +/// This class pulls the <see cref="JwtBearerOptions"/> instance registered by ASP.NET Core during the call to |
| 28 | +/// <see cref="JwtBearerExtensions.AddJwtBearer(AuthenticationBuilder, Action{JwtBearerOptions})">AddJwtBearer</see> |
| 29 | +/// for the default or configured authentication scheme and authenticates the token |
| 30 | +/// based on simplified logic used by <see cref="JwtBearerHandler"/>. |
| 31 | +/// </item> |
| 32 | +/// <item> |
| 33 | +/// The expected format of the payload is <c>{"Authorization":"Bearer TOKEN"}</c> where TOKEN is the JSON Web Token (JWT), |
| 34 | +/// mirroring the format of the 'Authorization' HTTP header. |
| 35 | +/// </item> |
| 36 | +/// <item> |
| 37 | +/// Events configured in <see cref="JwtBearerOptions.Events"/> are not raised by this implementation. |
| 38 | +/// </item> |
| 39 | +/// <item> |
| 40 | +/// Implementation does not call <see cref="Microsoft.Extensions.Logging.ILogger"/> to log authentication events. |
| 41 | +/// </item> |
| 42 | +/// </list> |
| 43 | +/// </summary> |
| 44 | +public class JwtWebSocketAuthenticationService : IWebSocketAuthenticationService |
| 45 | +{ |
| 46 | + private readonly IGraphQLSerializer _graphQLSerializer; |
| 47 | + private readonly IOptionsMonitor<JwtBearerOptions> _jwtBearerOptionsMonitor; |
| 48 | + private readonly string[] _defaultAuthenticationSchemes; |
| 49 | + |
| 50 | + /// <summary> |
| 51 | + /// Initializes a new instance of the <see cref="JwtWebSocketAuthenticationService"/> class. |
| 52 | + /// </summary> |
| 53 | + public JwtWebSocketAuthenticationService(IGraphQLSerializer graphQLSerializer, IOptionsMonitor<JwtBearerOptions> jwtBearerOptionsMonitor, IOptions<AuthenticationOptions> authenticationOptions) |
| 54 | + { |
| 55 | + _graphQLSerializer = graphQLSerializer; |
| 56 | + _jwtBearerOptionsMonitor = jwtBearerOptionsMonitor; |
| 57 | + var defaultAuthenticationScheme = authenticationOptions.Value.DefaultScheme; |
| 58 | + _defaultAuthenticationSchemes = defaultAuthenticationScheme != null ? [defaultAuthenticationScheme] : []; |
| 59 | + } |
| 60 | + |
| 61 | + /// <inheritdoc/> |
| 62 | + public async Task AuthenticateAsync(AuthenticationRequest authenticationRequest) |
| 63 | + { |
| 64 | + var connection = authenticationRequest.Connection; |
| 65 | + var operationMessage = authenticationRequest.OperationMessage; |
| 66 | + var schemes = authenticationRequest.AuthenticationSchemes.Any() ? authenticationRequest.AuthenticationSchemes : _defaultAuthenticationSchemes; |
| 67 | + try { |
| 68 | + // for connections authenticated via HTTP headers, no need to reauthenticate |
| 69 | + if (connection.HttpContext.User.Identity?.IsAuthenticated ?? false) |
| 70 | + return; |
| 71 | + |
| 72 | + // attempt to read the 'Authorization' key from the payload object and verify it contains "Bearer XXXXXXXX" |
| 73 | + var authPayload = _graphQLSerializer.ReadNode<AuthPayload>(operationMessage.Payload); |
| 74 | + if (authPayload != null && authPayload.Authorization != null && authPayload.Authorization.StartsWith("Bearer ", StringComparison.Ordinal)) { |
| 75 | + // pull the token from the value |
| 76 | + var token = authPayload.Authorization.Substring(7); |
| 77 | + |
| 78 | + // try to authenticate with each of the configured authentication schemes |
| 79 | + foreach (var scheme in schemes) { |
| 80 | + var options = _jwtBearerOptionsMonitor.Get(scheme); |
| 81 | + |
| 82 | + // follow logic simplified from JwtBearerHandler.HandleAuthenticateAsync, as follows: |
| 83 | + var tokenValidationParameters = await SetupTokenValidationParametersAsync(options, connection.HttpContext).ConfigureAwait(false); |
| 84 | +#if NET8_0_OR_GREATER |
| 85 | + if (!options.UseSecurityTokenValidators) { |
| 86 | + foreach (var tokenHandler in options.TokenHandlers) { |
| 87 | + try { |
| 88 | + var tokenValidationResult = await tokenHandler.ValidateTokenAsync(token, tokenValidationParameters).ConfigureAwait(false); |
| 89 | + if (tokenValidationResult.IsValid) { |
| 90 | + var principal = new ClaimsPrincipal(tokenValidationResult.ClaimsIdentity); |
| 91 | + // set the ClaimsPrincipal for the HttpContext; authentication will take place against this object |
| 92 | + connection.HttpContext.User = principal; |
| 93 | + return; |
| 94 | + } |
| 95 | + } catch { |
| 96 | + // no errors during authentication should throw an exception |
| 97 | + // specifically, attempting to validate an invalid JWT token may result in an exception |
| 98 | + } |
| 99 | + } |
| 100 | + } else { |
| 101 | +#else |
| 102 | + { |
| 103 | +#endif |
| 104 | +#pragma warning disable CS0618 // Type or member is obsolete |
| 105 | + foreach (var validator in options.SecurityTokenValidators) { |
| 106 | + if (validator.CanReadToken(token)) { |
| 107 | + try { |
| 108 | + var principal = validator.ValidateToken(token, tokenValidationParameters, out _); |
| 109 | + // set the ClaimsPrincipal for the HttpContext; authentication will take place against this object |
| 110 | + connection.HttpContext.User = principal; |
| 111 | + return; |
| 112 | + } catch { |
| 113 | + // no errors during authentication should throw an exception |
| 114 | + // specifically, attempting to validate an invalid JWT token will result in an exception |
| 115 | + } |
| 116 | + } |
| 117 | + } |
| 118 | +#pragma warning restore CS0618 // Type or member is obsolete |
| 119 | + } |
| 120 | + } |
| 121 | + } |
| 122 | + } catch { |
| 123 | + // no errors during authentication should throw an exception |
| 124 | + // specifically, parsing invalid JSON will result in an exception |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + private static async ValueTask<TokenValidationParameters> SetupTokenValidationParametersAsync(JwtBearerOptions options, HttpContext httpContext) |
| 129 | + { |
| 130 | + // Clone to avoid cross request race conditions for updated configurations. |
| 131 | + var tokenValidationParameters = options.TokenValidationParameters.Clone(); |
| 132 | + |
| 133 | +#if NET8_0_OR_GREATER |
| 134 | + if (options.ConfigurationManager is BaseConfigurationManager baseConfigurationManager) { |
| 135 | + tokenValidationParameters.ConfigurationManager = baseConfigurationManager; |
| 136 | + } else { |
| 137 | +#else |
| 138 | + { |
| 139 | +#endif |
| 140 | + if (options.ConfigurationManager != null) { |
| 141 | + // GetConfigurationAsync has a time interval that must pass before new http request will be issued. |
| 142 | + var configuration = await options.ConfigurationManager.GetConfigurationAsync(httpContext.RequestAborted).ConfigureAwait(false); |
| 143 | + var issuers = new[] { configuration.Issuer }; |
| 144 | + tokenValidationParameters.ValidIssuers = (tokenValidationParameters.ValidIssuers == null ? issuers : tokenValidationParameters.ValidIssuers.Concat(issuers)); |
| 145 | + tokenValidationParameters.IssuerSigningKeys = (tokenValidationParameters.IssuerSigningKeys == null ? configuration.SigningKeys : tokenValidationParameters.IssuerSigningKeys.Concat(configuration.SigningKeys)); |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + return tokenValidationParameters; |
| 150 | + } |
| 151 | + |
| 152 | +#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member |
| 153 | + public sealed class AuthPayload |
| 154 | + { |
| 155 | + public string? Authorization { get; set; } |
| 156 | + } |
| 157 | +#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member |
| 158 | +} |
0 commit comments