microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
Libraries/Microsoft.Teams.Plugins/Microsoft.Teams.Plugins.AspNetCore/Extensions/TokenValidator.cs
47lines · modecode
| 1 | using System.Collections.Concurrent; |
| 2 | |
| 3 | using Microsoft.AspNetCore.Authentication.JwtBearer; |
| 4 | using Microsoft.IdentityModel.Protocols; |
| 5 | using Microsoft.IdentityModel.Protocols.OpenIdConnect; |
| 6 | using Microsoft.IdentityModel.Tokens; |
| 7 | using Microsoft.IdentityModel.Validators; |
| 8 | |
| 9 | namespace Microsoft.Teams.Plugins.AspNetCore.Extensions; |
| 10 | public static class TokenValidator |
| 11 | { |
| 12 | private static readonly ConcurrentDictionary<string, IConfigurationManager<OpenIdConnectConfiguration>> _openIdMetadataCache = new(); |
| 13 | |
| 14 | // Add more options to configure other token types |
| 15 | public static void ConfigureValidation(JwtBearerOptions options, IEnumerable<string> validIssuers, IEnumerable<string> validAudiences, |
| 16 | string? openIdMetadataUrl = null) |
| 17 | { |
| 18 | options.SaveToken = true; |
| 19 | |
| 20 | options.TokenValidationParameters = new TokenValidationParameters |
| 21 | { |
| 22 | ValidateIssuer = validIssuers.Any(), |
| 23 | ValidateAudience = true, |
| 24 | ValidateLifetime = true, |
| 25 | ValidateIssuerSigningKey = true, |
| 26 | RequireSignedTokens = true, |
| 27 | ClockSkew = TimeSpan.FromMinutes(5), |
| 28 | ValidIssuers = validIssuers, |
| 29 | ValidAudiences = validAudiences, |
| 30 | }; |
| 31 | |
| 32 | // stricter validation: ensures the key’s issuer matches the token issuer |
| 33 | options.TokenValidationParameters.EnableAadSigningKeyIssuerValidation(); |
| 34 | |
| 35 | // use cached OpenID Connect metadata |
| 36 | if (openIdMetadataUrl != null) |
| 37 | { |
| 38 | options.ConfigurationManager = _openIdMetadataCache.GetOrAdd( |
| 39 | openIdMetadataUrl, |
| 40 | key => new ConfigurationManager<OpenIdConnectConfiguration>( |
| 41 | openIdMetadataUrl, new OpenIdConnectConfigurationRetriever(), new HttpClient()) |
| 42 | { |
| 43 | AutomaticRefreshInterval = BaseConfigurationManager.DefaultAutomaticRefreshInterval |
| 44 | }); |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |