|
| 1 | +using System.Diagnostics; |
1 | 2 | using System.Security.Claims; |
2 | 3 | using System.Text.Encodings.Web; |
3 | 4 |
|
@@ -38,37 +39,108 @@ public SecurityKeyAuthenticationHandler( |
38 | 39 | /// </returns> |
39 | 40 | protected override async Task<AuthenticateResult> HandleAuthenticateAsync() |
40 | 41 | { |
41 | | - // Resolve provider when configured; otherwise use the default registration. |
42 | | - var keyExtractor = string.IsNullOrEmpty(Options.ProviderServiceKey) |
43 | | - ? Context.RequestServices.GetRequiredService<ISecurityKeyExtractor>() |
44 | | - : Context.RequestServices.GetRequiredKeyedService<ISecurityKeyExtractor>(Options.ProviderServiceKey); |
| 42 | + var startTimestamp = 0L; |
| 43 | + Activity? activity = null; |
45 | 44 |
|
46 | | - // Extract the security key from the request using the configured extractor |
47 | | - var securityKey = keyExtractor.GetKey(Context); |
| 45 | + try |
| 46 | + { |
| 47 | + // Resolve provider when configured; otherwise use the default registration. |
| 48 | + var keyExtractor = string.IsNullOrEmpty(Options.ProviderServiceKey) |
| 49 | + ? Context.RequestServices.GetRequiredService<ISecurityKeyExtractor>() |
| 50 | + : Context.RequestServices.GetRequiredKeyedService<ISecurityKeyExtractor>(Options.ProviderServiceKey); |
| 51 | + |
| 52 | + // Extract the security key from the request using the configured extractor |
| 53 | + var securityKey = keyExtractor.GetKey(Context); |
| 54 | + |
| 55 | + // If no security key is provided, return no result |
| 56 | + if (string.IsNullOrEmpty(securityKey)) |
| 57 | + return AuthenticateResult.NoResult(); |
| 58 | + |
| 59 | + startTimestamp = Stopwatch.GetTimestamp(); |
| 60 | + activity = SecurityKeyDiagnostics.ActivitySource.StartActivity(SecurityKeyDiagnostics.AuthenticationActivityName, ActivityKind.Server); |
| 61 | + |
| 62 | + activity?.SetTag(SecurityKeyDiagnostics.AuthenticationSchemeTagName, Scheme.Name); |
| 63 | + |
| 64 | + var ipAddress = keyExtractor.GetRemoteAddress(Context); |
| 65 | + |
| 66 | + // Resolve provider when configured; otherwise use the default registration. |
| 67 | + var keyValidator = string.IsNullOrEmpty(Options.ProviderServiceKey) |
| 68 | + ? Context.RequestServices.GetRequiredService<ISecurityKeyValidator>() |
| 69 | + : Context.RequestServices.GetRequiredKeyedService<ISecurityKeyValidator>(Options.ProviderServiceKey); |
| 70 | + |
| 71 | + // Authenticate the security key and get the claims identity |
| 72 | + var identity = await keyValidator.Authenticate(securityKey, ipAddress, Scheme.Name, Context.RequestAborted); |
| 73 | + var securityKeyHash = SecurityKeyDiagnostics.ComputeSecurityKeyHash(securityKey); |
| 74 | + |
| 75 | + if (!identity.IsAuthenticated) |
| 76 | + { |
| 77 | + Logger.LogWarning("Invalid security key {SecurityKey} from IP {IPAddress}", securityKey, ipAddress); |
| 78 | + |
| 79 | + return CompleteAuthentication( |
| 80 | + result: InvalidSecurityKey, |
| 81 | + activity: activity, |
| 82 | + startTimestamp: startTimestamp, |
| 83 | + authenticationResult: SecurityKeyDiagnostics.AuthenticationResultFailure, |
| 84 | + securityKeyHash: securityKeyHash, |
| 85 | + failureReason: SecurityKeyDiagnostics.InvalidSecurityKeyFailureReason); |
| 86 | + } |
48 | 87 |
|
49 | | - // If no security key is provided, return no result |
50 | | - if (string.IsNullOrEmpty(securityKey)) |
51 | | - return AuthenticateResult.NoResult(); |
| 88 | + // create a user claim for the security key |
| 89 | + var principal = new ClaimsPrincipal(identity); |
| 90 | + var ticket = new AuthenticationTicket(principal, Scheme.Name); |
52 | 91 |
|
53 | | - var ipAddress = keyExtractor.GetRemoteAddress(Context); |
| 92 | + return CompleteAuthentication( |
| 93 | + result: AuthenticateResult.Success(ticket), |
| 94 | + activity: activity, |
| 95 | + startTimestamp: startTimestamp, |
| 96 | + authenticationResult: SecurityKeyDiagnostics.AuthenticationResultSuccess, |
| 97 | + securityKeyHash: securityKeyHash); |
54 | 98 |
|
55 | | - // Resolve provider when configured; otherwise use the default registration. |
56 | | - var keyValidator = string.IsNullOrEmpty(Options.ProviderServiceKey) |
57 | | - ? Context.RequestServices.GetRequiredService<ISecurityKeyValidator>() |
58 | | - : Context.RequestServices.GetRequiredKeyedService<ISecurityKeyValidator>(Options.ProviderServiceKey); |
| 99 | + } |
| 100 | + catch (Exception ex) when (ex is not OperationCanceledException) |
| 101 | + { |
| 102 | + activity?.AddException(ex); |
| 103 | + |
| 104 | + CompleteAuthentication( |
| 105 | + result: AuthenticateResult.Fail(ex), |
| 106 | + activity: activity, |
| 107 | + startTimestamp: startTimestamp, |
| 108 | + authenticationResult: SecurityKeyDiagnostics.AuthenticationResultFailure, |
| 109 | + failureReason: SecurityKeyDiagnostics.AuthenticationErrorFailureReason); |
59 | 110 |
|
60 | | - // Authenticate the security key and get the claims identity |
61 | | - var identity = await keyValidator.Authenticate(securityKey, ipAddress, Scheme.Name, Context.RequestAborted); |
62 | | - if (!identity.IsAuthenticated) |
| 111 | + throw; |
| 112 | + } |
| 113 | + finally |
63 | 114 | { |
64 | | - Logger.LogWarning("Invalid security key {SecurityKey} from IP {IPAddress}", securityKey, ipAddress); |
65 | | - return InvalidSecurityKey; |
| 115 | + activity?.Dispose(); |
66 | 116 | } |
| 117 | + } |
| 118 | + |
| 119 | + private static AuthenticateResult CompleteAuthentication( |
| 120 | + AuthenticateResult result, |
| 121 | + Activity? activity, |
| 122 | + long startTimestamp, |
| 123 | + string authenticationResult, |
| 124 | + string? securityKeyHash = null, |
| 125 | + string? failureReason = null) |
| 126 | + { |
| 127 | + activity?.SetTag(SecurityKeyDiagnostics.AuthenticationResultTagName, authenticationResult); |
| 128 | + |
| 129 | + if (securityKeyHash is not null) |
| 130 | + activity?.SetTag(SecurityKeyDiagnostics.SecurityKeyHashTagName, securityKeyHash); |
| 131 | + |
| 132 | + if (failureReason is not null) |
| 133 | + activity?.SetTag(SecurityKeyDiagnostics.AuthenticationFailureReasonTagName, failureReason); |
| 134 | + |
| 135 | + if (authenticationResult == SecurityKeyDiagnostics.AuthenticationResultFailure) |
| 136 | + activity?.SetStatus(ActivityStatusCode.Error, failureReason); |
67 | 137 |
|
68 | | - // create a user claim for the security key |
69 | | - var principal = new ClaimsPrincipal(identity); |
70 | | - var ticket = new AuthenticationTicket(principal, Scheme.Name); |
| 138 | + SecurityKeyDiagnostics.RecordAuthenticationMetrics( |
| 139 | + startTimestamp: startTimestamp, |
| 140 | + authenticationResult: authenticationResult, |
| 141 | + failureReason: failureReason, |
| 142 | + securityKeyHash: securityKeyHash); |
71 | 143 |
|
72 | | - return AuthenticateResult.Success(ticket); |
| 144 | + return result; |
73 | 145 | } |
74 | 146 | } |
0 commit comments