Repository navigation
Expand file tree
/
Copy pathTenantAuthenticationRegistration.cs
More file actions
166 lines (154 loc) · 7.28 KB
/
Copy pathTenantAuthenticationRegistration.cs
File metadata and controls
166 lines (154 loc) · 7.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
using LearnStack.Api.Tenancy;
using LearnStack.SharedKernel.Time;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
namespace LearnStack.Api.Authentication;
/// <summary>The single closed tenant scheme activated with the complete P02b-5 HTTP boundary.</summary>
internal static class TenantAuthenticationRegistration
{
internal const string Scheme = "TenantBearer";
internal static IServiceCollection AddLearnStackTenantAuthentication(
this IServiceCollection services, TenantAuthenticationOptions settings)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(settings);
IdentityModelEventSource.ShowPII = false;
IdentityModelEventSource.LogCompleteSecurityArtifact = false;
services.AddSingleton(settings);
services.TryAddSingleton<IClock, SystemClock>();
services.AddSingleton<TenantAuthenticationBackchannel>();
services.AddLogging();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = Scheme;
options.DefaultChallengeScheme = Scheme;
}).AddJwtBearer(Scheme, _ => { });
services.AddOptions<JwtBearerOptions>(Scheme)
.Configure<TenantAuthenticationBackchannel, IClock, ILogger<TenantAuthenticationEvents>>(
(options, backchannel, clock, logger) =>
{
options.Authority = settings.Issuer;
options.MetadataAddress = settings.MetadataAddress;
options.RequireHttpsMetadata = new Uri(settings.Issuer).Scheme == Uri.UriSchemeHttps;
options.MapInboundClaims = false;
options.SaveToken = false;
options.IncludeErrorDetails = false;
options.Backchannel = backchannel.Client;
options.BackchannelTimeout = TenantAuthenticationBackchannel.Timeout;
options.AutomaticRefreshInterval = TimeSpan.FromMinutes(5);
options.RefreshInterval = TimeSpan.FromSeconds(30);
options.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(
settings.MetadataAddress,
new OpenIdConnectConfigurationRetriever(),
new TenantOidcDocumentRetriever(settings, backchannel),
new TenantOidcConfigurationValidator(settings))
{
AutomaticRefreshInterval = options.AutomaticRefreshInterval,
RefreshInterval = options.RefreshInterval,
UseLastKnownGoodConfiguration = false,
};
options.TokenValidationParameters = new TokenValidationParameters
{
RequireSignedTokens = true,
TryAllIssuerSigningKeys = false,
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidIssuer = settings.Issuer,
ValidateAudience = true,
RequireAudience = true,
ValidAudience = TenantAuthenticationOptions.Audience,
IgnoreTrailingSlashWhenValidatingAudience = false,
RequireExpirationTime = true,
ValidateLifetime = true,
ClockSkew = TenantAuthenticationOptions.ClockSkew,
ValidAlgorithms = [SecurityAlgorithms.RsaSha256],
ValidTypes = ["JWT"],
LogValidationExceptions = false,
LogTokenId = false,
IncludeTokenOnFailedValidation = false,
};
options.Events = new TenantAuthenticationEvents(settings, clock, logger);
});
return services;
}
}
/// <summary>Only stock cryptographic validation publishes typed provider-subject evidence.</summary>
internal sealed class TenantAuthenticationEvents(
TenantAuthenticationOptions settings,
IClock clock,
ILogger<TenantAuthenticationEvents> logger) : JwtBearerEvents
{
public override Task MessageReceived(MessageReceivedContext context)
{
if (!HostClassificationMiddleware.ClassifiesPath(context.Request.Path)
|| context.HttpContext.Features.Get<HostClassification>() is null)
{
context.NoResult();
return Task.CompletedTask;
}
var values = context.Request.Headers.Authorization;
var present = context.Request.Headers.ContainsKey("Authorization");
context.HttpContext.Features.Set(new TenantCredentialFeature());
if (!present)
{
context.NoResult();
}
else if (values.Count != 1 || !TryToken(values[0], out var token)
|| !TenantTokenProfile.HasClosedJoseHeader(token))
{
TenantAuthenticationDiagnostics.Outcome(logger, TenantAuthenticationOutcome.CredentialRejected);
context.Fail("Tenant credential refused.");
}
else
{
context.Token = token;
}
return Task.CompletedTask;
}
public override Task TokenValidated(TokenValidatedContext context)
{
var feature = context.HttpContext.Features.Get<TenantCredentialFeature>();
if (feature is null || context.SecurityToken is not JsonWebToken token
|| !TenantTokenProfile.TryReadValidated(
token.EncodedToken, settings, clock.UtcNow, out var identity, out _))
{
TenantAuthenticationDiagnostics.Outcome(logger, TenantAuthenticationOutcome.ProfileRejected);
context.Fail("Tenant credential refused.");
}
else
{
feature.VerifiedSubject = identity;
TenantAuthenticationDiagnostics.Outcome(logger, TenantAuthenticationOutcome.ValidationAccepted);
}
return Task.CompletedTask;
}
public override Task AuthenticationFailed(AuthenticationFailedContext context)
{
if (context.HttpContext.Features.Get<TenantCredentialFeature>() is { } feature)
{
feature.Identity = null;
feature.VerifiedSubject = null;
}
TenantAuthenticationDiagnostics.Outcome(logger, TenantAuthenticationOutcome.ValidationRejected);
// Replace the returned failure too: base-handler event 7 sees its message.
context.Fail("Tenant credential refused.");
return Task.CompletedTask;
}
private static bool TryToken(string? header, out string token)
{
token = string.Empty;
const string prefix = "Bearer ";
if (header is null || !header.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)
|| header.Length > TenantAuthenticationOptions.MaxTokenBytes + prefix.Length)
{
return false;
}
token = header[prefix.Length..];
return token.Length > 0 && !token.Any(char.IsWhiteSpace) && !token.Contains(',');
}
}