-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAuthenticationExtensions.cs
More file actions
149 lines (130 loc) · 5.91 KB
/
Copy pathAuthenticationExtensions.cs
File metadata and controls
149 lines (130 loc) · 5.91 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
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2025-Present Datadog, Inc.
*/
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
#pragma warning disable CA5400, CA2000
namespace Stickerlandia.PrintService.Api.Configurations;
internal static class AuthenticationExtensions
{
public static IServiceCollection AddPrintServiceAuthentication(
this IServiceCollection services,
IConfiguration configuration)
{
var authMode = configuration.GetValue<string>("Authentication:Mode") ?? "SymmetricKey";
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// Prevent mapping "role" → long ClaimTypes.Role URI so that
// RoleClaimType = "role" matches the actual JWT claim name.
options.MapInboundClaims = false;
if (authMode.Equals("OidcDiscovery", StringComparison.OrdinalIgnoreCase))
{
ConfigureOidcDiscovery(options, configuration);
}
else
{
ConfigureSymmetricKey(options, configuration);
}
})
.AddScheme<AuthenticationSchemeOptions, PrinterKeyAuthenticationHandler>(
PrinterKeyAuthenticationHandler.SchemeName,
_ => { });
services.AddAuthorization();
return services;
}
private static void ConfigureOidcDiscovery(JwtBearerOptions options, IConfiguration configuration)
{
var authority = configuration["Authentication:Authority"]
?? throw new InvalidOperationException("Authentication:Authority is required for OIDC mode");
var audience = configuration["Authentication:Audience"] ?? "stickerlandia";
var requireHttpsMetadata = configuration.GetValue<bool>("Authentication:RequireHttpsMetadata", true);
// MetadataAddress allows using an internal URL for OIDC discovery (e.g., Docker network)
// while validating against the external issuer URL in the token
var metadataAddress = configuration["Authentication:MetadataAddress"];
// Ensure authority has trailing slash to match OpenIddict's issuer format (RFC 3986)
if (!authority.EndsWith('/'))
{
authority += "/";
}
options.Audience = audience;
options.RequireHttpsMetadata = requireHttpsMetadata;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = authority,
ValidateAudience = true,
ValidAudience = audience,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ClockSkew = TimeSpan.FromMinutes(5),
RoleClaimType = "role"
};
// If a separate metadata address is configured, use it for all OIDC fetching
// This is needed in Docker where internal URLs differ from external issuer URLs
if (!string.IsNullOrEmpty(metadataAddress))
{
if (!metadataAddress.EndsWith('/'))
{
metadataAddress += "/";
}
var httpHandler = new HttpClientHandler();
if (!requireHttpsMetadata)
{
httpHandler.ServerCertificateCustomValidationCallback = (_, _, _, _) => true;
}
// Do NOT use 'using var' here — the HttpClient is captured by the
// IssuerSigningKeyResolver lambda and must survive beyond this method.
var httpClient = new HttpClient(httpHandler);
var internalJwksUrl = metadataAddress + ".well-known/jwks";
// Use IssuerSigningKeyResolver to dynamically fetch keys from internal URL
options.TokenValidationParameters.IssuerSigningKeyResolver = (token, securityToken, kid, parameters) =>
{
// Fetch JWKS from internal URL synchronously (cached by HttpClient)
var jwksResponse = httpClient.GetStringAsync(new Uri(internalJwksUrl)).GetAwaiter().GetResult();
var jwks = new JsonWebKeySet(jwksResponse);
return jwks.Keys;
};
}
else
{
options.Authority = authority;
// For testing with WireMock over HTTP
if (!requireHttpsMetadata)
{
options.BackchannelHttpHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
};
}
}
}
private static void ConfigureSymmetricKey(JwtBearerOptions options, IConfiguration configuration)
{
var issuer = configuration["Jwt:Issuer"]
?? Environment.GetEnvironmentVariable("JWT_ISSUER")
?? "https://stickerlandia.local";
var audience = configuration["Jwt:Audience"]
?? Environment.GetEnvironmentVariable("JWT_AUDIENCE")
?? "stickerlandia";
var signingKey = configuration["Jwt:SigningKey"]
?? "DRjd/GnduI3Efzen9V9BvbNUfc/VKgXltV7Kbk9sMkY=";
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = issuer,
ValidateAudience = true,
ValidAudience = audience,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Convert.FromBase64String(signingKey)),
ClockSkew = TimeSpan.FromMinutes(5),
RoleClaimType = "role"
};
}
}