-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathMockOidcServer.cs
More file actions
300 lines (265 loc) · 10.6 KB
/
Copy pathMockOidcServer.cs
File metadata and controls
300 lines (265 loc) · 10.6 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
namespace ServiceControl.AcceptanceTesting.OpenIdConnect
{
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Tokens;
/// <summary>
/// A mock OpenID Connect server for acceptance testing.
/// Provides OIDC discovery endpoints and can generate valid JWT tokens.
/// </summary>
public class MockOidcServer : IDisposable
{
readonly HttpListener listener;
readonly RSA rsaKey;
readonly RsaSecurityKey securityKey;
readonly string keyId;
readonly CancellationTokenSource cts = new();
bool disposed;
public string Authority { get; }
public string Audience { get; }
public int Port { get; }
public MockOidcServer(int port = 0, string audience = "api://test-audience")
{
// Use a random port if 0 is specified
Port = port == 0 ? GetAvailablePort() : port;
Authority = $"http://localhost:{Port}";
Audience = audience;
// Generate RSA key pair for signing tokens
rsaKey = RSA.Create(2048);
keyId = Guid.NewGuid().ToString("N")[..16];
securityKey = new RsaSecurityKey(rsaKey) { KeyId = keyId };
listener = new HttpListener();
listener.Prefixes.Add($"{Authority}/");
}
static int GetAvailablePort()
{
// Find an available port by binding to port 0
using var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
public void Start()
{
listener.Start();
_ = Task.Run(async () =>
{
while (!cts.Token.IsCancellationRequested)
{
try
{
var context = await listener.GetContextAsync();
_ = Task.Run(() => HandleRequest(context));
}
catch (HttpListenerException) when (cts.Token.IsCancellationRequested)
{
// Expected when stopping
break;
}
catch (ObjectDisposedException)
{
// Expected when stopping
break;
}
}
});
}
void HandleRequest(HttpListenerContext context)
{
var path = context.Request.Url?.AbsolutePath ?? "";
var response = context.Response;
try
{
if (path == "/.well-known/openid-configuration")
{
ServeDiscoveryDocument(response);
}
else if (path is "/.well-known/jwks" or "/jwks")
{
ServeJwks(response);
}
else
{
response.StatusCode = 404;
response.Close();
}
}
catch
{
response.StatusCode = 500;
response.Close();
}
}
void ServeDiscoveryDocument(HttpListenerResponse response)
{
var discovery = new Dictionary<string, object>
{
["issuer"] = Authority,
["authorization_endpoint"] = $"{Authority}/authorize",
["token_endpoint"] = $"{Authority}/token",
["jwks_uri"] = $"{Authority}/.well-known/jwks",
["response_types_supported"] = new[] { "code", "token", "id_token" },
["subject_types_supported"] = new[] { "public" },
["id_token_signing_alg_values_supported"] = new[] { "RS256" },
["scopes_supported"] = new[] { "openid", "profile", "email" },
["token_endpoint_auth_methods_supported"] = new[] { "client_secret_basic", "client_secret_post" },
["claims_supported"] = new[] { "sub", "iss", "aud", "exp", "iat", "name", "email" }
};
var json = JsonSerializer.Serialize(discovery);
WriteJsonResponse(response, json);
}
void ServeJwks(HttpListenerResponse response)
{
var parameters = rsaKey.ExportParameters(false);
var jwk = new Dictionary<string, object>
{
["kty"] = "RSA",
["use"] = "sig",
["kid"] = keyId,
["alg"] = "RS256",
["n"] = Base64UrlEncode(parameters.Modulus),
["e"] = Base64UrlEncode(parameters.Exponent)
};
var jwks = new Dictionary<string, object>
{
["keys"] = new[] { jwk }
};
var json = JsonSerializer.Serialize(jwks);
WriteJsonResponse(response, json);
}
static void WriteJsonResponse(HttpListenerResponse response, string json)
{
response.ContentType = "application/json";
response.StatusCode = 200;
var buffer = Encoding.UTF8.GetBytes(json);
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.Close();
}
static string Base64UrlEncode(byte[] data)
{
return Convert.ToBase64String(data)
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
}
/// <summary>
/// Generates a valid JWT token signed by this mock server.
/// </summary>
/// <param name="subject">The subject (sub) claim</param>
/// <param name="expiresIn">Token lifetime</param>
/// <param name="additionalClaims">Additional claims to include</param>
/// <returns>A signed JWT token string</returns>
public string GenerateToken(
string subject = "test-user",
TimeSpan? expiresIn = null,
IEnumerable<Claim> additionalClaims = null)
{
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256);
// sub + preferred_username are required by PermissionVerbHandler for the audit log;
// defaulting them here keeps callers concise. Callers that need to test the
// missing-claim path pass an explicit additionalClaim with an empty value to override.
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, subject),
new("preferred_username", subject),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
if (additionalClaims != null)
{
claims.AddRange(additionalClaims);
}
var token = new JwtSecurityToken(
issuer: Authority,
audience: Audience,
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.Add(expiresIn ?? TimeSpan.FromHours(1)),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
/// <summary>
/// Generates an expired JWT token for testing token expiration.
/// </summary>
public string GenerateExpiredToken(string subject = "test-user")
{
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256);
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, subject),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(
issuer: Authority,
audience: Audience,
claims: claims,
notBefore: DateTime.UtcNow.AddHours(-2),
expires: DateTime.UtcNow.AddHours(-1),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
/// <summary>
/// Generates a token with an invalid audience.
/// </summary>
public string GenerateTokenWithWrongAudience(string subject = "test-user")
{
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256);
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, subject),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(
issuer: Authority,
audience: "wrong-audience",
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
/// <summary>
/// Generates a token with an invalid issuer.
/// </summary>
public string GenerateTokenWithWrongIssuer(string subject = "test-user")
{
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256);
var claims = new List<Claim>
{
new(JwtRegisteredClaimNames.Sub, subject),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(
issuer: "https://wrong-issuer.example.com",
audience: Audience,
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
public void Dispose()
{
if (!disposed)
{
cts.Cancel();
listener.Stop();
listener.Close();
rsaKey.Dispose();
cts.Dispose();
disposed = true;
}
// Prevent finalizer from running since we've already cleaned up managed resources
GC.SuppressFinalize(this);
}
}
}