Skip to content

Commit 51ea2cc

Browse files
committed
refact classes
1 parent d940668 commit 51ea2cc

File tree

1 file changed

+12
-41
lines changed

1 file changed

+12
-41
lines changed
Lines changed: 12 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,28 @@
11
using System;
22
using System.Collections.Generic;
33
using System.Net.Http;
4-
using System.Threading.Tasks;
54
using Microsoft.AspNetCore.Authentication.JwtBearer;
6-
using Microsoft.IdentityModel.Tokens;
5+
using Microsoft.IdentityModel.Protocols;
6+
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
77

88
namespace NetDevPack.Security.JwtExtensions
99
{
1010
public static class JwksExtension
1111
{
1212
public static void SetJwksOptions(this JwtBearerOptions options, JwkOptions jwkOptions)
1313
{
14-
15-
if (options.TokenValidationParameters == null)
16-
options.TokenValidationParameters = new TokenValidationParameters();
17-
18-
if (options.TokenValidationParameters.IssuerSigningKeyResolver == null)
19-
options.TokenValidationParameters.IssuerSigningKeyResolver = new JwkRetriever(jwkOptions).IssuerSigningKeyResolver;
20-
14+
var httpClient = new HttpClient(options.BackchannelHttpHandler ?? new HttpClientHandler())
15+
{
16+
Timeout = options.BackchannelTimeout,
17+
MaxResponseContentBufferSize = 1024 * 1024 * 10 // 10 MB
18+
};
19+
20+
options.ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(
21+
jwkOptions.JwksUri.OriginalString,
22+
new JwksRetriever(),
23+
new HttpDocumentRetriever(httpClient) { RequireHttps = options.RequireHttpsMetadata });
2124
options.TokenValidationParameters.ValidateAudience = false;
2225
options.TokenValidationParameters.ValidIssuer = jwkOptions.Issuer;
2326
}
24-
25-
public class JwkRetriever
26-
{
27-
private static readonly HttpClient HttpClient = new HttpClient();
28-
29-
public JwkRetriever(JwkOptions jwkOptions)
30-
{
31-
Options = jwkOptions;
32-
}
33-
34-
public JwkOptions Options { get; }
35-
public JwkList LastResponse { get; private set; }
36-
public IEnumerable<SecurityKey> IssuerSigningKeyResolver(string token, SecurityToken securityToken, string kid, TokenValidationParameters validationParameters)
37-
{
38-
if (LastResponse == null || LastResponse.When.Add(Options.KeepFor) < DateTime.Now)
39-
{
40-
var jwkTask = GetJwks();
41-
jwkTask.Wait();
42-
LastResponse = new JwkList(jwkTask.Result);
43-
}
44-
45-
return LastResponse.Jwks.Keys;
46-
}
47-
48-
private async Task<JsonWebKeySet> GetJwks()
49-
{
50-
var response = await HttpClient.GetAsync(Options.JwksUri);
51-
var responseString = await response.Content.ReadAsStringAsync();
52-
return new JsonWebKeySet(responseString);
53-
54-
}
55-
}
5627
}
5728
}

0 commit comments

Comments
 (0)