|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +using Microsoft.Agents.Authentication; |
| 5 | +using Microsoft.AspNetCore.Authentication.JwtBearer; |
| 6 | +using Microsoft.Extensions.Configuration; |
| 7 | +using Microsoft.Extensions.DependencyInjection; |
| 8 | +using Microsoft.Extensions.Logging; |
| 9 | +using Microsoft.IdentityModel.Protocols; |
| 10 | +using Microsoft.IdentityModel.Protocols.OpenIdConnect; |
| 11 | +using Microsoft.IdentityModel.Tokens; |
| 12 | +using Microsoft.IdentityModel.Validators; |
| 13 | +using System; |
| 14 | +using System.Collections.Concurrent; |
| 15 | +using System.Collections.Generic; |
| 16 | +using System.Globalization; |
| 17 | +using System.IdentityModel.Tokens.Jwt; |
| 18 | +using System.Linq; |
| 19 | +using System.Net.Http; |
| 20 | +using System.Threading.Tasks; |
| 21 | + |
| 22 | +namespace TeamsAgent; |
| 23 | + |
| 24 | +public static class AspNetExtensions |
| 25 | +{ |
| 26 | + private static readonly ConcurrentDictionary<string, ConfigurationManager<OpenIdConnectConfiguration>> _openIdMetadataCache = new(); |
| 27 | + |
| 28 | + /// <summary> |
| 29 | + /// Adds token validation typical for ABS/SMBA and agent-to-agent. |
| 30 | + /// default to Azure Public Cloud. |
| 31 | + /// </summary> |
| 32 | + /// <param name="services"></param> |
| 33 | + /// <param name="configuration"></param> |
| 34 | + /// <param name="tokenValidationSectionName">Name of the config section to read.</param> |
| 35 | + /// <param name="logger">Optional logger to use for authentication event logging.</param> |
| 36 | + /// <remarks> |
| 37 | + /// Configuration: |
| 38 | + /// <code> |
| 39 | + /// "TokenValidation": { |
| 40 | + /// "Audiences": [ |
| 41 | + /// "{required:agent-appid}" |
| 42 | + /// ], |
| 43 | + /// "TenantId": "{recommended:tenant-id}", |
| 44 | + /// "ValidIssuers": [ |
| 45 | + /// "{default:Public-AzureBotService}" |
| 46 | + /// ], |
| 47 | + /// "IsGov": {optional:false}, |
| 48 | + /// "AzureBotServiceOpenIdMetadataUrl": optional, |
| 49 | + /// "OpenIdMetadataUrl": optional, |
| 50 | + /// "AzureBotServiceTokenHandling": "{optional:true}" |
| 51 | + /// "OpenIdMetadataRefresh": "optional-12:00:00" |
| 52 | + /// } |
| 53 | + /// </code> |
| 54 | + /// |
| 55 | + /// `IsGov` can be omitted, in which case public Azure Bot Service and Azure Cloud metadata urls are used. |
| 56 | + /// `ValidIssuers` can be omitted, in which case the Public Azure Bot Service issuers are used. |
| 57 | + /// `TenantId` can be omitted if the Agent is not being called by another Agent. Otherwise it is used to add other known issuers. Only when `ValidIssuers` is omitted. |
| 58 | + /// `AzureBotServiceOpenIdMetadataUrl` can be omitted. In which case default values in combination with `IsGov` is used. |
| 59 | + /// `OpenIdMetadataUrl` can be omitted. In which case default values in combination with `IsGov` is used. |
| 60 | + /// `AzureBotServiceTokenHandling` defaults to true and should always be true until Azure Bot Service sends Entra ID token. |
| 61 | + /// </remarks> |
| 62 | + public static void AddAgentAspNetAuthentication(this IServiceCollection services, IConfiguration configuration, string tokenValidationSectionName = "TokenValidation", ILogger logger = null!) |
| 63 | + { |
| 64 | + IConfigurationSection tokenValidationSection = configuration.GetSection(tokenValidationSectionName); |
| 65 | + List<string> validTokenIssuers = tokenValidationSection.GetSection("ValidIssuers").Get<List<string>>()!; |
| 66 | + List<string> audiences = tokenValidationSection.GetSection("Audiences").Get<List<string>>()!; |
| 67 | + |
| 68 | + if (!tokenValidationSection.Exists()) |
| 69 | + { |
| 70 | + logger?.LogError("Missing configuration section '{tokenValidationSectionName}'. This section is required to be present in appsettings.json", tokenValidationSectionName); |
| 71 | + throw new InvalidOperationException($"Missing configuration section '{tokenValidationSectionName}'. This section is required to be present in appsettings.json"); |
| 72 | + } |
| 73 | + |
| 74 | + // If ValidIssuers is empty, default for ABS Public Cloud |
| 75 | + if (validTokenIssuers == null || validTokenIssuers.Count == 0) |
| 76 | + { |
| 77 | + validTokenIssuers = |
| 78 | + [ |
| 79 | + "https://api.botframework.com", |
| 80 | + "https://sts.windows.net/d6d49420-f39b-4df7-a1dc-d59a935871db/", |
| 81 | + "https://login.microsoftonline.com/d6d49420-f39b-4df7-a1dc-d59a935871db/v2.0", |
| 82 | + "https://sts.windows.net/f8cdef31-a31e-4b4a-93e4-5f571e91255a/", |
| 83 | + "https://login.microsoftonline.com/f8cdef31-a31e-4b4a-93e4-5f571e91255a/v2.0", |
| 84 | + "https://sts.windows.net/69e9b82d-4842-4902-8d1e-abc5b98a55e8/", |
| 85 | + "https://login.microsoftonline.com/69e9b82d-4842-4902-8d1e-abc5b98a55e8/v2.0", |
| 86 | + ]; |
| 87 | + |
| 88 | + string? tenantId = tokenValidationSection["TenantId"]; |
| 89 | + if (!string.IsNullOrEmpty(tenantId)) |
| 90 | + { |
| 91 | + validTokenIssuers.Add(string.Format(CultureInfo.InvariantCulture, AuthenticationConstants.ValidTokenIssuerUrlTemplateV1, tenantId)); |
| 92 | + validTokenIssuers.Add(string.Format(CultureInfo.InvariantCulture, AuthenticationConstants.ValidTokenIssuerUrlTemplateV2, tenantId)); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + if (audiences == null || audiences.Count == 0) |
| 97 | + { |
| 98 | + throw new ArgumentException($"{tokenValidationSectionName}:Audiences requires at least one value"); |
| 99 | + } |
| 100 | + |
| 101 | + bool isGov = tokenValidationSection.GetValue("IsGov", false); |
| 102 | + bool azureBotServiceTokenHandling = tokenValidationSection.GetValue("AzureBotServiceTokenHandling", true); |
| 103 | + |
| 104 | + // If the `AzureBotServiceOpenIdMetadataUrl` setting is not specified, use the default based on `IsGov`. This is what is used to authenticate ABS tokens. |
| 105 | + string? azureBotServiceOpenIdMetadataUrl = tokenValidationSection["AzureBotServiceOpenIdMetadataUrl"]; |
| 106 | + if (string.IsNullOrEmpty(azureBotServiceOpenIdMetadataUrl)) |
| 107 | + { |
| 108 | + azureBotServiceOpenIdMetadataUrl = isGov ? AuthenticationConstants.GovAzureBotServiceOpenIdMetadataUrl : AuthenticationConstants.PublicAzureBotServiceOpenIdMetadataUrl; |
| 109 | + } |
| 110 | + |
| 111 | + // If the `OpenIdMetadataUrl` setting is not specified, use the default based on `IsGov`. This is what is used to authenticate Entra ID tokens. |
| 112 | + string? openIdMetadataUrl = tokenValidationSection["OpenIdMetadataUrl"]; |
| 113 | + if (string.IsNullOrEmpty(openIdMetadataUrl)) |
| 114 | + { |
| 115 | + openIdMetadataUrl = isGov ? AuthenticationConstants.GovOpenIdMetadataUrl : AuthenticationConstants.PublicOpenIdMetadataUrl; |
| 116 | + } |
| 117 | + |
| 118 | + TimeSpan openIdRefreshInterval = tokenValidationSection.GetValue("OpenIdMetadataRefresh", BaseConfigurationManager.DefaultAutomaticRefreshInterval); |
| 119 | + |
| 120 | + _ = services.AddAuthentication(options => |
| 121 | + { |
| 122 | + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; |
| 123 | + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; |
| 124 | + }) |
| 125 | + .AddJwtBearer(options => |
| 126 | + { |
| 127 | + options.SaveToken = true; |
| 128 | + options.TokenValidationParameters = new TokenValidationParameters |
| 129 | + { |
| 130 | + ValidateIssuer = true, |
| 131 | + ValidateAudience = true, |
| 132 | + ValidateLifetime = true, |
| 133 | + ClockSkew = TimeSpan.FromMinutes(5), |
| 134 | + ValidIssuers = validTokenIssuers, |
| 135 | + ValidAudiences = audiences, |
| 136 | + ValidateIssuerSigningKey = true, |
| 137 | + RequireSignedTokens = true, |
| 138 | + }; |
| 139 | + |
| 140 | + // Using Microsoft.IdentityModel.Validators |
| 141 | + options.TokenValidationParameters.EnableAadSigningKeyIssuerValidation(); |
| 142 | + |
| 143 | + options.Events = new JwtBearerEvents |
| 144 | + { |
| 145 | + // Create a ConfigurationManager based on the requestor. This is to handle ABS non-Entra tokens. |
| 146 | + OnMessageReceived = async context => |
| 147 | + { |
| 148 | + string authorizationHeader = context.Request.Headers.Authorization.ToString(); |
| 149 | + |
| 150 | + if (string.IsNullOrEmpty(authorizationHeader)) |
| 151 | + { |
| 152 | + // Default to AadTokenValidation handling |
| 153 | + context.Options.TokenValidationParameters.ConfigurationManager ??= options.ConfigurationManager as BaseConfigurationManager; |
| 154 | + await Task.CompletedTask.ConfigureAwait(false); |
| 155 | + return; |
| 156 | + } |
| 157 | + |
| 158 | + string[]? parts = authorizationHeader?.Split(' '); |
| 159 | + if (parts?.Length != 2 || parts[0] != "Bearer") |
| 160 | + { |
| 161 | + // Default to AadTokenValidation handling |
| 162 | + context.Options.TokenValidationParameters.ConfigurationManager ??= options.ConfigurationManager as BaseConfigurationManager; |
| 163 | + await Task.CompletedTask.ConfigureAwait(false); |
| 164 | + return; |
| 165 | + } |
| 166 | + |
| 167 | + JwtSecurityToken? token = new(parts[1]); |
| 168 | + string issuer = token.Claims.FirstOrDefault(claim => claim.Type == AuthenticationConstants.IssuerClaim)?.Value!; |
| 169 | + |
| 170 | + if (azureBotServiceTokenHandling && AuthenticationConstants.BotFrameworkTokenIssuer.Equals(issuer)) |
| 171 | + { |
| 172 | + // Use the Azure Bot authority for this configuration manager |
| 173 | + context.Options.TokenValidationParameters.ConfigurationManager = _openIdMetadataCache.GetOrAdd(azureBotServiceOpenIdMetadataUrl, key => |
| 174 | + { |
| 175 | + return new ConfigurationManager<OpenIdConnectConfiguration>(azureBotServiceOpenIdMetadataUrl, new OpenIdConnectConfigurationRetriever(), new HttpClient()) |
| 176 | + { |
| 177 | + AutomaticRefreshInterval = openIdRefreshInterval |
| 178 | + }; |
| 179 | + }); |
| 180 | + } |
| 181 | + else |
| 182 | + { |
| 183 | + context.Options.TokenValidationParameters.ConfigurationManager = _openIdMetadataCache.GetOrAdd(openIdMetadataUrl, key => |
| 184 | + { |
| 185 | + return new ConfigurationManager<OpenIdConnectConfiguration>(openIdMetadataUrl, new OpenIdConnectConfigurationRetriever(), new HttpClient()) |
| 186 | + { |
| 187 | + AutomaticRefreshInterval = openIdRefreshInterval |
| 188 | + }; |
| 189 | + }); |
| 190 | + } |
| 191 | + |
| 192 | + await Task.CompletedTask.ConfigureAwait(false); |
| 193 | + }, |
| 194 | + |
| 195 | + OnTokenValidated = context => |
| 196 | + { |
| 197 | + logger?.LogDebug("TOKEN Validated"); |
| 198 | + return Task.CompletedTask; |
| 199 | + }, |
| 200 | + OnForbidden = context => |
| 201 | + { |
| 202 | + logger?.LogWarning("Forbidden: {m}", context.Result.ToString()); |
| 203 | + return Task.CompletedTask; |
| 204 | + }, |
| 205 | + OnAuthenticationFailed = context => |
| 206 | + { |
| 207 | + logger?.LogWarning("Auth Failed {m}", context.Exception.ToString()); |
| 208 | + return Task.CompletedTask; |
| 209 | + } |
| 210 | + }; |
| 211 | + }); |
| 212 | + } |
| 213 | +} |
0 commit comments