-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathUserTokenEndpointService.cs
More file actions
206 lines (174 loc) · 7.87 KB
/
UserTokenEndpointService.cs
File metadata and controls
206 lines (174 loc) · 7.87 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
// 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 Duende.IdentityModel.Client;
using Duende.IdentityModel;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Duende.AccessTokenManagement.OpenIdConnect;
/// <summary>
/// Implements token endpoint operations using IdentityModel
/// </summary>
public class UserTokenEndpointService : IUserTokenEndpointService
{
private readonly IOpenIdConnectConfigurationService _configurationService;
private readonly IClientAssertionService _clientAssertionService;
private readonly IDPoPProofService _dPoPProofService;
private readonly ILogger<UserTokenEndpointService> _logger;
private readonly UserTokenManagementOptions _options;
/// <summary>
/// ctor
/// </summary>
/// <param name="options"></param>
/// <param name="clientAssertionService"></param>
/// <param name="dPoPProofService"></param>
/// <param name="logger"></param>
/// <param name="configurationService"></param>
public UserTokenEndpointService(
IOpenIdConnectConfigurationService configurationService,
IOptions<UserTokenManagementOptions> options,
IClientAssertionService clientAssertionService,
IDPoPProofService dPoPProofService,
ILogger<UserTokenEndpointService> logger)
{
_configurationService = configurationService;
_options = options.Value;
_clientAssertionService = clientAssertionService;
_dPoPProofService = dPoPProofService;
_logger = logger;
}
/// <inheritdoc/>
public async Task<UserToken> RefreshAccessTokenAsync(
UserToken userToken,
UserTokenRequestParameters parameters,
CancellationToken cancellationToken = default)
{
var refreshToken = userToken.RefreshToken ?? throw new ArgumentNullException(nameof(userToken.RefreshToken));
_logger.LogTrace("Refreshing refresh token: {token}", refreshToken);
var oidc = await _configurationService.GetOpenIdConnectConfigurationAsync(parameters.ChallengeScheme).ConfigureAwait(false);
var request = new RefreshTokenRequest
{
Address = oidc.TokenEndpoint,
ClientId = oidc.ClientId!,
ClientSecret = oidc.ClientSecret,
ClientCredentialStyle = _options.ClientCredentialStyle,
RefreshToken = refreshToken
};
request.Options.TryAdd(ClientCredentialsTokenManagementDefaults.TokenRequestParametersOptionsName, parameters);
if (!string.IsNullOrWhiteSpace(parameters.Scope))
{
request.Scope = parameters.Scope;
}
if (!string.IsNullOrEmpty(parameters.Resource))
{
request.Resource.Add(parameters.Resource);
}
if (parameters.Assertion != null)
{
request.ClientAssertion = parameters.Assertion;
request.ClientCredentialStyle = ClientCredentialStyle.PostBody;
}
else
{
var assertion = await _clientAssertionService.GetClientAssertionAsync(OpenIdConnectTokenManagementDefaults.ClientCredentialsClientNamePrefix + oidc.Scheme, parameters).ConfigureAwait(false);
if (assertion != null)
{
request.ClientAssertion = assertion;
request.ClientCredentialStyle = ClientCredentialStyle.PostBody;
}
}
var dPoPJsonWebKey = userToken.DPoPJsonWebKey;
if (dPoPJsonWebKey != null)
{
var proof = await _dPoPProofService.CreateProofTokenAsync(new DPoPProofRequest
{
Url = request.Address!,
Method = "POST",
DPoPJsonWebKey = dPoPJsonWebKey,
});
request.DPoPProofToken = proof?.ProofToken;
}
_logger.LogDebug("refresh token request to: {endpoint}", request.Address);
var response = await oidc.HttpClient!.RequestRefreshTokenAsync(request, cancellationToken).ConfigureAwait(false);
if (response.IsError &&
(response.Error == OidcConstants.TokenErrors.UseDPoPNonce || response.Error == OidcConstants.TokenErrors.InvalidDPoPProof) &&
dPoPJsonWebKey != null &&
response.DPoPNonce != null)
{
_logger.LogDebug("DPoP error during token refresh. Retrying with server nonce");
var proof = await _dPoPProofService.CreateProofTokenAsync(new DPoPProofRequest
{
Url = request.Address!,
Method = "POST",
DPoPJsonWebKey = dPoPJsonWebKey,
DPoPNonce = response.DPoPNonce
});
request.DPoPProofToken = proof?.ProofToken;
if (request.DPoPProofToken != null)
{
response = await oidc.HttpClient!.RequestRefreshTokenAsync(request, cancellationToken).ConfigureAwait(false);
}
}
var token = new UserToken();
if (response.IsError)
{
token.Error = response.Error;
}
else
{
token.IdentityToken = response.IdentityToken;
token.AccessToken = response.AccessToken;
token.AccessTokenType = response.TokenType;
token.DPoPJsonWebKey = dPoPJsonWebKey;
token.Expiration = response.ExpiresIn == 0
? DateTimeOffset.MaxValue
: DateTimeOffset.UtcNow.AddSeconds(response.ExpiresIn);
token.RefreshToken = response.RefreshToken ?? userToken.RefreshToken;
token.Scope = response.Scope;
}
return token;
}
/// <inheritdoc/>
public async Task RevokeRefreshTokenAsync(
UserToken userToken,
UserTokenRequestParameters parameters,
CancellationToken cancellationToken = default)
{
var refreshToken = userToken.RefreshToken ?? throw new ArgumentNullException(nameof(userToken.RefreshToken));
_logger.LogTrace("Revoking refresh token: {token}", refreshToken);
var oidc = await _configurationService.GetOpenIdConnectConfigurationAsync(parameters.ChallengeScheme).ConfigureAwait(false);
if (string.IsNullOrEmpty(oidc.RevocationEndpoint))
{
throw new InvalidOperationException("Revocation endpoint not configured");
}
var request = new TokenRevocationRequest
{
Address = oidc.RevocationEndpoint,
ClientId = oidc.ClientId!,
ClientSecret = oidc.ClientSecret,
ClientCredentialStyle = _options.ClientCredentialStyle,
Token = refreshToken,
TokenTypeHint = OidcConstants.TokenTypes.RefreshToken
};
request.Options.TryAdd(ClientCredentialsTokenManagementDefaults.TokenRequestParametersOptionsName, parameters);
if (parameters.Assertion != null)
{
request.ClientAssertion = parameters.Assertion;
request.ClientCredentialStyle = ClientCredentialStyle.PostBody;
}
else
{
var assertion = await _clientAssertionService.GetClientAssertionAsync(OpenIdConnectTokenManagementDefaults.ClientCredentialsClientNamePrefix + oidc.Scheme, parameters).ConfigureAwait(false);
if (assertion != null)
{
request.ClientAssertion = assertion;
request.ClientCredentialStyle = ClientCredentialStyle.PostBody;
}
}
_logger.LogDebug("token revocation request to: {endpoint}", request.Address);
var response = await oidc.HttpClient!.RevokeTokenAsync(request, cancellationToken).ConfigureAwait(false);
if (response.IsError)
{
_logger.LogInformation("Error revoking refresh token. Error = {error}", response.Error);
}
}
}