-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathOidcClient.cs
491 lines (411 loc) · 19.6 KB
/
OidcClient.cs
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
// Copyright (c) Duende Software. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Security.Claims;
using Duende.IdentityModel.OidcClient.Browser;
using Duende.IdentityModel.OidcClient.Infrastructure;
using Duende.IdentityModel.OidcClient.Results;
using Duende.IdentityModel;
using Duende.IdentityModel.Client;
using Microsoft.Extensions.Logging;
namespace Duende.IdentityModel.OidcClient
{
/// <summary>
/// OpenID Connect client
/// </summary>
public class OidcClient
{
private readonly ILogger _logger;
private readonly AuthorizeClient _authorizeClient;
private readonly bool _useDiscovery;
private readonly ResponseProcessor _processor;
/// <summary>
/// Gets the options.
/// </summary>
/// <value>
/// The options.
/// </value>
public OidcClientOptions Options { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="OidcClient"/> class.
/// </summary>
/// <param name="options">The options.</param>
/// <exception cref="System.ArgumentNullException">options</exception>
public OidcClient(OidcClientOptions options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
if (options.ProviderInformation == null)
{
if (options.Authority.IsMissing()) throw new ArgumentException("No authority specified", nameof(Options.Authority));
_useDiscovery = true;
}
Options = options;
_logger = options.LoggerFactory.CreateLogger<OidcClient>();
_authorizeClient = new AuthorizeClient(options);
_processor = new ResponseProcessor(options, EnsureProviderInformationAsync);
}
/// <summary>
/// Starts a login.
/// </summary>
/// <param name="request">The login request.</param>
/// <param name="cancellationToken">A token that can be used to cancel the request</param>
/// <returns></returns>
public virtual async Task<LoginResult> LoginAsync(LoginRequest request = null, CancellationToken cancellationToken = default)
{
_logger.LogTrace("LoginAsync");
_logger.LogInformation("Starting authentication request.");
if (request == null) request = new LoginRequest();
await EnsureConfigurationAsync(cancellationToken);
var authorizeResult = await _authorizeClient.AuthorizeAsync(new AuthorizeRequest
{
DisplayMode = request.BrowserDisplayMode,
Timeout = request.BrowserTimeout,
ExtraParameters = request.FrontChannelExtraParameters
}, cancellationToken);
if (authorizeResult.IsError)
{
return new LoginResult(authorizeResult.Error, authorizeResult.ErrorDescription);
}
var result = await ProcessResponseAsync(
authorizeResult.Data,
authorizeResult.State,
request.BackChannelExtraParameters,
cancellationToken);
if (!result.IsError)
{
_logger.LogInformation("Authentication request success.");
}
return result;
}
/// <summary>
/// Prepares the login request.
/// </summary>
/// <param name="frontChannelParameters">extra parameters to send to the authorize endpoint.</param>
/// /// <param name="cancellationToken">A token that can be used to cancel the request</param>
/// <returns>State for initiating the authorize request and processing the response</returns>
public virtual async Task<AuthorizeState> PrepareLoginAsync(Parameters frontChannelParameters = null, CancellationToken cancellationToken = default)
{
_logger.LogTrace("PrepareLoginAsync");
await EnsureConfigurationAsync(cancellationToken);
return await _authorizeClient.CreateAuthorizeStateAsync(frontChannelParameters);
}
/// <summary>
/// Creates a logout URL.
/// </summary>
/// <param name="request">The logout request.</param>
/// /// <param name="cancellationToken">A token that can be used to cancel the request</param>
/// <returns></returns>
public virtual async Task<string> PrepareLogoutAsync(LogoutRequest request = default, CancellationToken cancellationToken = default)
{
await EnsureConfigurationAsync(cancellationToken);
var endpoint = Options.ProviderInformation.EndSessionEndpoint;
if (endpoint.IsMissing())
{
throw new InvalidOperationException("Discovery document has no end session endpoint");
}
return _authorizeClient.CreateEndSessionUrl(endpoint, request);
}
/// <summary>
/// Starts a logout.
/// </summary>
/// <param name="request">The logout request.</param>
/// <param name="cancellationToken">A token that can be used to cancel the request</param>
/// <returns></returns>
public virtual async Task<LogoutResult> LogoutAsync(LogoutRequest request = null, CancellationToken cancellationToken = default)
{
if (request == null) request = new LogoutRequest();
await EnsureConfigurationAsync(cancellationToken);
var result = await _authorizeClient.EndSessionAsync(request, cancellationToken);
if (result.ResultType != BrowserResultType.Success)
{
return new LogoutResult(result.ResultType.ToString())
{
Response = result.Response
};
}
else
{
return new LogoutResult
{
Response = result.Response
};
}
}
/// <summary>
/// Processes the authorize response.
/// </summary>
/// <param name="data">The response data.</param>
/// <param name="state">The state.</param>
/// <param name="backChannelParameters">Parameters for back-channel call</param>
/// <param name="cancellationToken">A token that can be used to cancel the request</param>
/// <returns>
/// Result of the login response validation
/// </returns>
public virtual async Task<LoginResult> ProcessResponseAsync(
string data,
AuthorizeState state,
Parameters backChannelParameters = null,
CancellationToken cancellationToken = default)
{
_logger.LogTrace("ProcessResponseAsync");
_logger.LogInformation("Processing response.");
backChannelParameters = backChannelParameters ?? new Parameters();
await EnsureConfigurationAsync(cancellationToken);
_logger.LogDebug("Authorize response: {response}", data);
var authorizeResponse = new AuthorizeResponse(data);
if (authorizeResponse.IsError)
{
_logger.LogError(authorizeResponse.Error);
return new LoginResult(authorizeResponse.Error, authorizeResponse.ErrorDescription);
}
var result = await _processor.ProcessResponseAsync(authorizeResponse, state, backChannelParameters, cancellationToken);
if (result.IsError)
{
_logger.LogError(result.Error);
return new LoginResult(result.Error, result.ErrorDescription);
}
var userInfoClaims = Enumerable.Empty<Claim>();
if (Options.LoadProfile)
{
var userInfoResult = await GetUserInfoAsync(result.TokenResponse.AccessToken, cancellationToken);
if (userInfoResult.IsError)
{
var error = $"Error contacting userinfo endpoint: {userInfoResult.Error}";
_logger.LogError(error);
return new LoginResult(error);
}
userInfoClaims = userInfoResult.Claims;
var userInfoSub = userInfoClaims.FirstOrDefault(c => c.Type == JwtClaimTypes.Subject);
if (userInfoSub == null)
{
var error = "sub claim is missing from userinfo endpoint";
_logger.LogError(error);
return new LoginResult(error);
}
if (result.TokenResponse.IdentityToken != null)
{
if (!string.Equals(userInfoSub.Value, result.User.FindFirst(JwtClaimTypes.Subject).Value))
{
var error = "sub claim from userinfo endpoint is different than sub claim from identity token.";
_logger.LogError(error);
return new LoginResult(error);
}
}
}
var authTimeValue = result.User.FindFirst(JwtClaimTypes.AuthenticationTime)?.Value;
DateTimeOffset? authTime = null;
if (authTimeValue.IsPresent() && long.TryParse(authTimeValue, out long seconds))
{
authTime = DateTimeOffset.FromUnixTimeSeconds(seconds);
}
var user = ProcessClaims(result.User, userInfoClaims);
var loginResult = new LoginResult
{
User = user,
AccessToken = result.TokenResponse.AccessToken,
RefreshToken = result.TokenResponse.RefreshToken,
AccessTokenExpiration = DateTimeOffset.Now.AddSeconds(result.TokenResponse.ExpiresIn),
IdentityToken = result.TokenResponse.IdentityToken,
AuthenticationTime = authTime,
TokenResponse = result.TokenResponse // In some cases there is additional custom response data that clients need access to
};
if (loginResult.RefreshToken.IsPresent())
{
loginResult.RefreshTokenHandler = new RefreshTokenDelegatingHandler(
this,
loginResult.AccessToken,
loginResult.RefreshToken,
loginResult.TokenResponse.TokenType,
Options.RefreshTokenInnerHttpHandler);
}
return loginResult;
}
/// <summary>
/// Gets the user claims from the userinfo endpoint.
/// </summary>
/// <param name="accessToken">The access token.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// User claims
/// </returns>
/// <exception cref="ArgumentNullException">accessToken</exception>
/// <exception cref="InvalidOperationException">No userinfo endpoint specified</exception>
public virtual async Task<UserInfoResult> GetUserInfoAsync(string accessToken, CancellationToken cancellationToken = default)
{
_logger.LogTrace("GetUserInfoAsync");
await EnsureConfigurationAsync(cancellationToken);
if (accessToken.IsMissing()) throw new ArgumentNullException(nameof(accessToken));
if (!Options.ProviderInformation.SupportsUserInfo) throw new InvalidOperationException("No userinfo endpoint specified");
var userInfoClient = Options.CreateClient();
var userInfoResponse = await userInfoClient.GetUserInfoAsync(new UserInfoRequest
{
Address = Options.ProviderInformation.UserInfoEndpoint,
Token = accessToken
}, cancellationToken).ConfigureAwait(false);
if (userInfoResponse.IsError)
{
return new UserInfoResult
{
Error = userInfoResponse.Error
};
}
return new UserInfoResult
{
Claims = userInfoResponse.Claims
};
}
/// <summary>
/// Refreshes an access token.
/// </summary>
/// <param name="refreshToken">The refresh token.</param>
/// <param name="backChannelParameters">Back-channel parameters</param>
/// <param name="scope">Space separated list of the requested scopes.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A token response.
/// </returns>
public virtual async Task<RefreshTokenResult> RefreshTokenAsync(
string refreshToken,
Parameters backChannelParameters = null,
string scope = null,
CancellationToken cancellationToken = default)
{
_logger.LogTrace("RefreshTokenAsync");
await EnsureConfigurationAsync(cancellationToken);
backChannelParameters = backChannelParameters ?? new Parameters();
var client = Options.CreateClient();
var response = await client.RequestRefreshTokenAsync(new RefreshTokenRequest
{
Address = Options.ProviderInformation.TokenEndpoint,
ClientId = Options.ClientId,
ClientSecret = Options.ClientSecret,
ClientAssertion = await Options.GetClientAssertionAsync(),
ClientCredentialStyle = Options.TokenClientCredentialStyle,
RefreshToken = refreshToken,
Parameters = backChannelParameters,
Scope = scope
}, cancellationToken).ConfigureAwait(false);
if (response.IsError)
{
return new RefreshTokenResult
{
Error = response.Error,
ErrorDescription = response.ErrorDescription,
};
}
// validate token response
var validationResult = await _processor.ValidateTokenResponseAsync(response, null, requireIdentityToken: Options.Policy.RequireIdentityTokenOnRefreshTokenResponse,
cancellationToken: cancellationToken);
if (validationResult.IsError)
{
return new RefreshTokenResult { Error = validationResult.Error };
}
return new RefreshTokenResult
{
IdentityToken = response.IdentityToken,
AccessToken = response.AccessToken,
RefreshToken = response.RefreshToken,
ExpiresIn = response.ExpiresIn,
AccessTokenExpiration = DateTimeOffset.Now.AddSeconds(response.ExpiresIn)
};
}
internal async Task EnsureConfigurationAsync(CancellationToken cancellationToken)
{
await EnsureProviderInformationAsync(cancellationToken);
_logger.LogTrace("Effective options:");
_logger.LogTrace(LogSerializer.Serialize(Options));
}
internal async Task EnsureProviderInformationAsync(CancellationToken cancellationToken)
{
_logger.LogTrace("EnsureProviderInformation");
if (_useDiscovery)
{
if (Options.RefreshDiscoveryDocumentForLogin == false)
{
// discovery document has been loaded before - skip reload
if (Options.ProviderInformation != null)
{
_logger.LogDebug("Skipping refresh of discovery document.");
return;
}
}
var discoveryClient = Options.CreateClient();
var disco = await discoveryClient.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest
{
Address = Options.Authority,
Policy = Options.Policy.Discovery
}, cancellationToken).ConfigureAwait(false);
if (disco.IsError)
{
_logger.LogError("Error loading discovery document: {errorType} - {error}", disco.ErrorType.ToString(), disco.Error);
if (disco.ErrorType == ResponseErrorType.Exception)
{
throw new InvalidOperationException("Error loading discovery document: " + disco.Error, disco.Exception);
}
throw new InvalidOperationException("Error loading discovery document: " + disco.Error);
}
_logger.LogDebug("Successfully loaded discovery document");
_logger.LogDebug("Loaded keyset from {jwks_uri}", disco.JwksUri);
var kids = disco.KeySet?.Keys?.Select(k => k.Kid);
if (kids != null)
{
_logger.LogDebug($"Keyset contains the following kids: {string.Join(",", kids)}");
}
Options.ProviderInformation = new ProviderInformation
{
IssuerName = disco.Issuer,
KeySet = disco.KeySet,
AuthorizeEndpoint = disco.AuthorizeEndpoint,
PushedAuthorizationRequestEndpoint = disco.PushedAuthorizationRequestEndpoint,
TokenEndpoint = disco.TokenEndpoint,
EndSessionEndpoint = disco.EndSessionEndpoint,
UserInfoEndpoint = disco.UserInfoEndpoint,
TokenEndPointAuthenticationMethods = disco.TokenEndpointAuthenticationMethodsSupported
};
}
if (Options.ProviderInformation.IssuerName.IsMissing())
{
var error = "Issuer name is missing in provider information";
_logger.LogError(error);
throw new InvalidOperationException(error);
}
if (Options.ProviderInformation.AuthorizeEndpoint.IsMissing())
{
var error = "Authorize endpoint is missing in provider information";
_logger.LogError(error);
throw new InvalidOperationException(error);
}
if (Options.ProviderInformation.TokenEndpoint.IsMissing())
{
var error = "Token endpoint is missing in provider information";
_logger.LogError(error);
throw new InvalidOperationException(error);
}
if (Options.ProviderInformation.KeySet == null)
{
if (Options.Policy.Discovery.RequireKeySet)
{
var error = "Key set is missing in provider information";
_logger.LogError(error);
throw new InvalidOperationException(error);
}
}
}
internal ClaimsPrincipal ProcessClaims(ClaimsPrincipal user, IEnumerable<Claim> userInfoClaims)
{
_logger.LogTrace("ProcessClaims");
var combinedClaims = new HashSet<Claim>(new ClaimComparer(new ClaimComparer.Options { IgnoreIssuer = true }));
user.Claims.ToList().ForEach(c => combinedClaims.Add(c));
userInfoClaims.ToList().ForEach(c => combinedClaims.Add(c));
List<Claim> userClaims;
if (Options.FilterClaims)
{
userClaims = combinedClaims.Where(c => !Options.FilteredClaims.Contains(c.Type)).ToList();
}
else
{
userClaims = combinedClaims.ToList();
}
return new ClaimsPrincipal(new ClaimsIdentity(userClaims, user.Identity.AuthenticationType, user.Identities.First().NameClaimType, user.Identities.First().RoleClaimType));
}
}
}