-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathClientTokenManagementApiTests.cs
More file actions
226 lines (193 loc) · 8.15 KB
/
ClientTokenManagementApiTests.cs
File metadata and controls
226 lines (193 loc) · 8.15 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
// 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.IdentityServer.Configuration;
using Duende.IdentityModel;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.Text.Json;
namespace Duende.AccessTokenManagement.Tests;
public class ClientTokenManagementApiTests(ITestOutputHelper output) : IntegrationTestBase(output), IAsyncLifetime
{
private static readonly string _jwkJson = CreateJWKJson();
private IClientCredentialsTokenManagementService _tokenService = null!;
private IHttpClientFactory _clientFactory = null!;
private ClientCredentialsClient _clientOptions = null!;
private static string CreateJWKJson()
{
var key = CryptoHelper.CreateRsaSecurityKey();
var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(key);
jwk.Alg = "RS256";
var jwkJson = JsonSerializer.Serialize(jwk);
return jwkJson;
}
public override async ValueTask InitializeAsync()
{
await base.InitializeAsync();
var services = new ServiceCollection();
services.AddDistributedMemoryCache();
services.AddClientCredentialsTokenManagement()
.AddClient("test", client =>
{
client.TokenEndpoint = "https://identityserver/connect/token";
client.ClientId = "client_credentials_client";
client.ClientSecret = "secret";
client.Scope = "scope1";
client.HttpClient = IdentityServerHost.HttpClient;
client.DPoPJsonWebKey = _jwkJson;
});
services.AddClientCredentialsHttpClient("test", "test")
.AddHttpMessageHandler(() =>
{
return new ApiHandler(ApiHost.Server.CreateHandler());
});
var provider = services.BuildServiceProvider();
_tokenService = provider.GetRequiredService<IClientCredentialsTokenManagementService>();
_clientFactory = provider.GetRequiredService<IHttpClientFactory>();
_clientOptions = provider.GetRequiredService<IOptionsMonitor<ClientCredentialsClient>>().Get("test");
}
public class ApiHandler : DelegatingHandler
{
private HttpMessageHandler? _innerHandler;
public ApiHandler(HttpMessageHandler innerHandler)
{
_innerHandler = innerHandler;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (_innerHandler != null)
{
InnerHandler = _innerHandler;
_innerHandler = null;
}
return base.SendAsync(request, cancellationToken);
}
}
[Fact]
public async Task api_returning_401_should_send_new_access_token()
{
var count = 0;
string? accessToken = null;
ApiHost.ApiInvoked += ctx =>
{
var at = ctx.Request.Headers.Authorization.FirstOrDefault()?.Split(' ', StringSplitOptions.RemoveEmptyEntries)?[1].Trim();
if (accessToken == null)
{
ApiHost.ApiStatusCodeToReturn = 401;
accessToken = at;
}
else
{
accessToken.ShouldNotBe(at);
}
count++;
};
var client = _clientFactory.CreateClient("test");
var apiResult = await client.GetAsync(ApiHost.Url("/test"));
count.ShouldBe(2);
}
[Fact]
public async Task dpop_clients_GetAccessTokenAsync_should_obtain_token_with_cnf()
{
var token = await _tokenService.GetAccessTokenAsync("test");
token.IsError.ShouldBeFalse();
token.DPoPJsonWebKey.ShouldNotBeNull();
token.AccessTokenType.ShouldBe("DPoP");
var payload = Base64UrlEncoder.Decode(token.AccessToken!.Split('.')[1]);
var values = JsonSerializer.Deserialize<Dictionary<string, object>>(payload);
values!.ShouldContainKey("cnf");
}
[Theory]
[InlineData("RS256")]
[InlineData("RS384")]
[InlineData("RS512")]
[InlineData("PS256")]
[InlineData("PS384")]
[InlineData("PS512")]
public async Task using_different_rsa_keys_for_dpop_should_obtain_token_with_cnf(string alg)
{
var key = CryptoHelper.CreateRsaSecurityKey();
var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(key);
jwk.Alg = alg;
var jwkJson = JsonSerializer.Serialize(jwk);
_clientOptions.DPoPJsonWebKey = jwkJson;
var token = await _tokenService.GetAccessTokenAsync("test");
token.IsError.ShouldBeFalse();
token.DPoPJsonWebKey.ShouldNotBeNull();
token.AccessTokenType.ShouldBe("DPoP");
var payload = Base64UrlEncoder.Decode(token.AccessToken!.Split('.')[1]);
var values = JsonSerializer.Deserialize<Dictionary<string, object>>(payload);
values!.ShouldContainKey("cnf");
var json = JsonSerializer.Deserialize<JsonElement>(values!["cnf"].ToString()!);
var jkt = json.GetString("jkt");
jkt.ShouldBe(Base64Url.Encode(jwk.ComputeJwkThumbprint()));
}
[Theory]
[InlineData("ES256")]
[InlineData("ES384")]
[InlineData("ES512")]
public async Task using_different_ec_keys_for_dpop_should_obtain_token_with_cnf(string alg)
{
var key = CryptoHelper.CreateECDsaSecurityKey();
var jwk = JsonWebKeyConverter.ConvertFromECDsaSecurityKey(key);
jwk.Alg = alg;
var jwkJson = JsonSerializer.Serialize(jwk);
_clientOptions.DPoPJsonWebKey = jwkJson;
var token = await _tokenService.GetAccessTokenAsync("test");
token.IsError.ShouldBeFalse();
token.DPoPJsonWebKey.ShouldNotBeNull();
token.AccessTokenType.ShouldBe("DPoP");
var payload = Base64UrlEncoder.Decode(token.AccessToken!.Split('.')[1]);
var values = JsonSerializer.Deserialize<Dictionary<string, object>>(payload);
values!.ShouldContainKey("cnf");
var json = JsonSerializer.Deserialize<JsonElement>(values!["cnf"].ToString()!);
var jkt = json.GetString("jkt");
jkt.ShouldBe(Base64Url.Encode(jwk.ComputeJwkThumbprint()));
}
[Fact]
public async Task dpop_tokens_should_be_passed_to_api()
{
string? scheme = null;
string? proofToken = null;
ApiHost.ApiInvoked += ctx =>
{
scheme = ctx.Request.Headers.Authorization.FirstOrDefault()?.Split(' ', StringSplitOptions.RemoveEmptyEntries)[0];
proofToken = ctx.Request.Headers["DPoP"].FirstOrDefault()?.ToString();
};
var client = _clientFactory.CreateClient("test");
var apiResult = await client.GetAsync(ApiHost.Url("/test"));
scheme.ShouldBe("DPoP");
proofToken.ShouldNotBeNull();
}
[Fact]
public async Task when_api_issues_nonce_api_request_should_be_retried_with_new_nonce()
{
string? proofToken = null;
var count = 0;
string? accessToken = null;
ApiHost.ApiInvoked += ctx =>
{
var at = ctx.Request.Headers.Authorization.FirstOrDefault()?.Split(' ', StringSplitOptions.RemoveEmptyEntries)?[1].Trim();
if (count == 0)
{
ApiHost.ApiStatusCodeToReturn = 401;
ctx.Response.Headers["WWW-Authenticate"] = "DPoP error=\"use_dpop_nonce\"";
ctx.Response.Headers["DPoP-Nonce"] = "some-nonce";
accessToken = at;
}
else
{
accessToken.ShouldBe(at);
}
proofToken = ctx.Request.Headers["DPoP"].FirstOrDefault()?.ToString();
count++;
};
var client = _clientFactory.CreateClient("test");
var apiResult = await client.GetAsync(ApiHost.Url("/test"));
count.ShouldBe(2);
var payload = Base64UrlEncoder.Decode(proofToken!.Split('.')[1]);
var values = JsonSerializer.Deserialize<Dictionary<string, object>>(payload);
values!["nonce"].ToString().ShouldBe("some-nonce");
}
}