|
1 | 1 | using System; |
2 | 2 | using System.Collections.Generic; |
3 | 3 | using System.Net.Http; |
4 | | -using System.Threading.Tasks; |
5 | 4 | using Microsoft.AspNetCore.Authentication.JwtBearer; |
6 | | -using Microsoft.IdentityModel.Tokens; |
| 5 | +using Microsoft.IdentityModel.Protocols; |
| 6 | +using Microsoft.IdentityModel.Protocols.OpenIdConnect; |
7 | 7 |
|
8 | 8 | namespace NetDevPack.Security.JwtExtensions |
9 | 9 | { |
10 | 10 | public static class JwksExtension |
11 | 11 | { |
12 | 12 | public static void SetJwksOptions(this JwtBearerOptions options, JwkOptions jwkOptions) |
13 | 13 | { |
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 }); |
21 | 24 | options.TokenValidationParameters.ValidateAudience = false; |
22 | 25 | options.TokenValidationParameters.ValidIssuer = jwkOptions.Issuer; |
23 | 26 | } |
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 | | - } |
56 | 27 | } |
57 | 28 | } |
0 commit comments