-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
374 lines (339 loc) · 16.5 KB
/
Copy pathProgram.cs
File metadata and controls
374 lines (339 loc) · 16.5 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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
using System.IdentityModel.Tokens.Jwt;
using System.Text.Json;
using API.Client.Models;
using API.Client.Services;
using Azure.Identity;
using Azure.Security.KeyVault.Keys.Cryptography;
namespace API.Client;
class Program
{
static async Task<int> Main(string[] args)
{
Console.WriteLine("=== OAuth 2.0 Private Key JWT Client ===\n");
// Parse CLI args. No args => existing client_credentials flow (unchanged).
// --gateway --api-client <id> [--api-client <id> ...] => gateway mode.
bool gatewayMode = false;
var apiClientIds = new List<string>();
string? standaloneClientId = null;
var configPath = "config.json";
for (int i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "--gateway":
gatewayMode = true;
break;
case "--api-client":
if (i + 1 >= args.Length)
{
Console.WriteLine("Error: --api-client requires a value");
PrintUsage();
return 2;
}
apiClientIds.Add(args[++i]);
break;
case "--client":
if (i + 1 >= args.Length)
{
Console.WriteLine("Error: --client requires a value");
PrintUsage();
return 2;
}
standaloneClientId = args[++i];
break;
case "--config":
if (i + 1 >= args.Length)
{
Console.WriteLine("Error: --config requires a value");
PrintUsage();
return 2;
}
configPath = args[++i];
break;
case "--help":
case "-h":
PrintUsage();
return 0;
default:
Console.WriteLine($"Error: Unknown argument '{args[i]}'");
PrintUsage();
return 2;
}
}
if (gatewayMode && apiClientIds.Count == 0)
{
Console.WriteLine("Error: --gateway requires at least one --api-client <id>");
PrintUsage();
return 2;
}
if (!gatewayMode && apiClientIds.Count > 0)
{
Console.WriteLine("Error: --api-client requires --gateway");
PrintUsage();
return 2;
}
if (gatewayMode && standaloneClientId != null)
{
Console.WriteLine("Error: --client cannot be combined with --gateway (use --api-client instead)");
PrintUsage();
return 2;
}
try
{
// Load configuration (path overridable via --config; defaults to config.json)
if (!File.Exists(configPath))
{
Console.WriteLine($"Error: Configuration file '{configPath}' not found.");
Console.WriteLine("Please create a config.json file based on config.json.template");
return 1;
}
Console.WriteLine($"Loading configuration from {configPath}...");
var configJson = await File.ReadAllTextAsync(configPath);
var config = JsonSerializer.Deserialize<OAuthConfig>(configJson);
if (config == null)
{
Console.WriteLine("Error: Failed to parse configuration file.");
return 1;
}
// tokenEndpoint is shared between both flows; everything else is mode-specific.
if (string.IsNullOrWhiteSpace(config.TokenEndpoint))
{
Console.WriteLine("Configuration Error: tokenEndpoint is required");
return 1;
}
// effectiveConfig is what JwtService + OAuthClient run against. In gateway mode it
// is built from the 'gateway' section; in standalone mode it is the top-level config.
OAuthConfig effectiveConfig;
List<(string Id, ApiClientConfig Config)> resolvedApiClients = new();
if (gatewayMode)
{
if (config.Gateway == null)
{
Console.WriteLine("Error: --gateway mode requires a 'gateway' section in config.json");
return 1;
}
Console.WriteLine("Validating gateway configuration...");
config.Gateway.Validate();
if (config.Gateway.ApiClients == null || config.Gateway.ApiClients.Count == 0)
{
Console.WriteLine("Error: 'gateway.apiClients' section is required when using --gateway");
return 1;
}
foreach (var id in apiClientIds)
{
if (!config.Gateway.ApiClients.TryGetValue(id, out var apiClient))
{
Console.WriteLine($"Error: API client '{id}' not found in config.json 'gateway.apiClients'");
Console.WriteLine($" Available: {string.Join(", ", config.Gateway.ApiClients.Keys)}");
return 1;
}
apiClient.Validate(id);
resolvedApiClients.Add((id, apiClient));
}
effectiveConfig = config.Gateway.ToOAuthConfig(config.TokenEndpoint);
Console.WriteLine("Configuration is valid.\n");
}
else
{
Console.WriteLine("Validating configuration...");
effectiveConfig = standaloneClientId != null
? config.ForStandaloneClient(standaloneClientId)
: config;
effectiveConfig.Validate();
Console.WriteLine("Configuration is valid.\n");
}
// Display configuration (without sensitive data)
Console.WriteLine("Configuration:");
Console.WriteLine($" Token Endpoint: {effectiveConfig.TokenEndpoint}");
Console.WriteLine($" Client ID: {effectiveConfig.ClientId}");
Console.WriteLine($" Audience: {effectiveConfig.Audience}");
Console.WriteLine($" Issuer: {effectiveConfig.Issuer}");
Console.WriteLine($" Scopes: {(string.IsNullOrEmpty(effectiveConfig.Scopes) ? "(none)" : effectiveConfig.Scopes)}");
if (effectiveConfig.UseKeyVault)
{
Console.WriteLine($" Key Vault URL: {effectiveConfig.KeyVaultUrl}");
Console.WriteLine($" Key Vault Key: {effectiveConfig.KeyVaultKeyName}");
if (!string.IsNullOrEmpty(effectiveConfig.KeyVaultKeyVersion))
Console.WriteLine($" Key Vault Key Version: {effectiveConfig.KeyVaultKeyVersion}");
}
else
{
Console.WriteLine($" Private Key Path: {effectiveConfig.PrivateKeyPath}");
}
if (!string.IsNullOrEmpty(effectiveConfig.KeyId))
{
Console.WriteLine($" Key ID: {effectiveConfig.KeyId}");
}
if (gatewayMode)
{
Console.WriteLine($" Mode: GATEWAY (token-exchange)");
Console.WriteLine($" API clients: {string.Join(", ", resolvedApiClients.Select(b => b.Id))}");
}
// Create services
CryptographyClient? cryptoClient = null;
if (effectiveConfig.UseKeyVault)
{
var keyVersion = string.IsNullOrEmpty(effectiveConfig.KeyVaultKeyVersion) ? "" : $"/{effectiveConfig.KeyVaultKeyVersion}";
var keyId = new Uri($"{effectiveConfig.KeyVaultUrl!.TrimEnd('/')}/keys/{effectiveConfig.KeyVaultKeyName}{keyVersion}");
cryptoClient = new CryptographyClient(keyId, new DefaultAzureCredential());
Console.WriteLine("\nKey Vault authentication via DefaultAzureCredential (Azure CLI / Managed Identity / environment).");
}
var jwtService = new JwtService(effectiveConfig, cryptoClient);
using var oauthClient = new OAuthClient(effectiveConfig, jwtService);
// Step 1: authenticate (gateway or standalone — same client_credentials call)
var stepLabel = gatewayMode ? "STEP 1: Gateway Authentication" : "Requesting Access Token...";
Console.WriteLine("\n" + new string('=', 60));
Console.WriteLine(stepLabel);
Console.WriteLine(new string('=', 60));
var tokenResponse = await oauthClient.RequestAccessTokenAsync();
Console.WriteLine("\n" + new string('=', 60));
Console.WriteLine(gatewayMode ? "SUCCESS - Gateway Access Token Received" : "SUCCESS - Access Token Received");
Console.WriteLine(new string('=', 60) + "\n");
// Use the explicit authority when configured; otherwise derive it from the token endpoint.
var realmUrl = string.IsNullOrWhiteSpace(effectiveConfig.Authority)
? effectiveConfig.TokenEndpoint.Replace("/protocol/openid-connect/token", "")
: effectiveConfig.Authority!;
PrintTokenSection(tokenResponse, realmUrl, effectiveConfig.ExpectedAudience, effectiveConfig.ClockSkewMinutes);
if (!gatewayMode)
{
return 0;
}
// Step 2: token exchange for each API client
int failures = 0;
for (int idx = 0; idx < resolvedApiClients.Count; idx++)
{
var (apiClientId, apiClient) = resolvedApiClients[idx];
Console.WriteLine("\n" + new string('=', 60));
Console.WriteLine($"STEP 2.{idx + 1}: Token Exchange - {apiClientId}");
Console.WriteLine(new string('=', 60));
try
{
var exchanged = await oauthClient.ExchangeTokenAsync(tokenResponse.AccessToken, apiClientId, apiClient);
Console.WriteLine("\n" + new string('=', 60));
Console.WriteLine($"SUCCESS - API Client Access Token Received ({apiClientId})");
Console.WriteLine(new string('=', 60) + "\n");
var expectedAud = apiClient.ExpectedAudience ?? apiClient.Audience;
PrintTokenSection(exchanged, realmUrl, expectedAud, effectiveConfig.ClockSkewMinutes);
}
catch (Exception ex)
{
failures++;
Console.WriteLine($"\nFAILED to exchange token for '{apiClientId}': {ex.Message}");
if (ex.InnerException != null)
{
Console.WriteLine($" Inner Error: {ex.InnerException.Message}");
}
// Continue with the remaining API clients.
}
}
if (failures > 0)
{
Console.WriteLine($"\n{failures} of {resolvedApiClients.Count} API client exchange(s) failed.");
return 1;
}
return 0;
}
catch (ArgumentException ex)
{
Console.WriteLine($"\nConfiguration Error: {ex.Message}");
return 1;
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"\nFile Error: {ex.Message}");
return 1;
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"\nOperation Error: {ex.Message}");
return 1;
}
catch (Exception ex)
{
Console.WriteLine($"\nError: {ex.Message}");
if (ex.InnerException != null)
{
Console.WriteLine($"Inner Error: {ex.InnerException.Message}");
}
return 1;
}
}
static void PrintTokenSection(TokenResponse tokenResponse, string realmUrl, string? expectedAudience, int? clockSkewMinutes = null)
{
Console.WriteLine("--- TOKEN VALIDATION ---");
var validationService = new TokenValidationService(realmUrl, expectedAudience, clockSkewMinutes);
var validationResult = validationService.ValidateTokenAsync(tokenResponse.AccessToken).GetAwaiter().GetResult();
if (validationResult.IsValid)
{
Console.WriteLine($" {validationResult.Message}");
Console.WriteLine(" - Signature: Valid");
Console.WriteLine($" - Issuer: Verified (Keycloak)");
var tokenAudience = validationResult.ValidatedToken?.Audiences.FirstOrDefault();
Console.WriteLine($" - Audience: Verified ({tokenAudience})");
Console.WriteLine(" - Expiration: Valid");
}
else
{
Console.WriteLine($" {validationResult.Message}");
Console.WriteLine("\nWARNING: Token validation failed! This token may be invalid or tampered with.");
}
Console.WriteLine();
Console.WriteLine("Token Type: " + (tokenResponse.TokenType ?? "Bearer"));
if (tokenResponse.ExpiresIn.HasValue)
{
Console.WriteLine($"Expires In: {tokenResponse.ExpiresIn.Value} seconds");
}
if (!string.IsNullOrEmpty(tokenResponse.Scope))
{
Console.WriteLine($"Scope: {tokenResponse.Scope}");
}
Console.WriteLine("\n--- ACCESS TOKEN JWT ---");
Console.WriteLine(tokenResponse.AccessToken);
Console.WriteLine("--- END ACCESS TOKEN JWT ---\n");
try
{
var handler = new JwtSecurityTokenHandler();
var jwtToken = handler.ReadJwtToken(tokenResponse.AccessToken);
Console.WriteLine("--- DECODED TOKEN CLAIMS ---");
foreach (var claim in jwtToken.Claims)
{
Console.WriteLine($" {claim.Type}: {claim.Value}");
}
Console.WriteLine("\n--- TOKEN HEADER ---");
Console.WriteLine($" Algorithm: {jwtToken.Header.Alg}");
Console.WriteLine($" Type: {jwtToken.Header.Typ}");
if (!string.IsNullOrEmpty(jwtToken.Header.Kid))
{
Console.WriteLine($" Key ID: {jwtToken.Header.Kid}");
}
Console.WriteLine("\n--- TOKEN VALIDITY ---");
Console.WriteLine($" Issued At: {jwtToken.ValidFrom:yyyy-MM-dd HH:mm:ss} UTC");
Console.WriteLine($" Expires: {jwtToken.ValidTo:yyyy-MM-dd HH:mm:ss} UTC");
var remaining = jwtToken.ValidTo - DateTime.UtcNow;
Console.WriteLine($" Time Remaining: {remaining.TotalMinutes:F2} minutes");
}
catch (Exception ex)
{
Console.WriteLine($"Note: Could not decode token (it may not be a JWT): {ex.Message}");
}
}
static void PrintUsage()
{
Console.WriteLine();
Console.WriteLine("Usage:");
Console.WriteLine(" API.client Run client_credentials flow (default)");
Console.WriteLine(" API.client --client <id> Standalone flow, but running as one of");
Console.WriteLine(" the named identities in config.json's");
Console.WriteLine(" 'standaloneClients' map instead of the");
Console.WriteLine(" top-level clientId");
Console.WriteLine(" API.client --gateway --api-client <id> [--api-client <id> ...]");
Console.WriteLine(" Gateway mode: authenticate using the");
Console.WriteLine(" 'gateway' section of config.json, then");
Console.WriteLine(" token-exchange (RFC 8693) for each API client");
Console.WriteLine(" API.client --config <path> Use an alternate configuration file (default: config.json)");
Console.WriteLine(" API.client --help Show this help");
Console.WriteLine();
Console.WriteLine("Standalone mode uses the top-level config.json fields (optionally overridden per-client via 'standaloneClients').");
Console.WriteLine("Gateway mode uses the 'gateway' section (its own clientId/key/audience + 'apiClients' map).");
}
}