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