microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
core/src/Microsoft.Teams.Core/Hosting/BotAuthenticationHandler.cs
138lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | using System.IdentityModel.Tokens.Jwt; |
| 5 | using System.Net.Http.Headers; |
| 6 | using Microsoft.Extensions.Logging; |
| 7 | using Microsoft.Extensions.Options; |
| 8 | using Microsoft.Identity.Abstractions; |
| 9 | using Microsoft.Identity.Web; |
| 10 | using Microsoft.Teams.Core.Schema; |
| 11 | |
| 12 | namespace Microsoft.Teams.Core.Hosting; |
| 13 | |
| 14 | /// <summary> |
| 15 | /// HTTP message handler that automatically acquires and attaches authentication tokens |
| 16 | /// for Bot Framework API calls. Supports both app-only and agentic (user-delegated) token acquisition. |
| 17 | /// </summary> |
| 18 | /// <remarks> |
| 19 | /// Initializes a new instance of the <see cref="BotAuthenticationHandler"/> class. |
| 20 | /// </remarks> |
| 21 | /// <param name="authorizationHeaderProvider">The authorization header provider for acquiring tokens.</param> |
| 22 | /// <param name="logger">The logger instance.</param> |
| 23 | /// <param name="authenticationOptionsName">The name of the MSAL configuration options to use for token acquisition. Defaults to "AzureAd".</param> |
| 24 | /// <param name="managedIdentityOptions">Optional managed identity options monitor. When the named entry matching <paramref name="authenticationOptionsName"/> has a non-empty <c>UserAssignedClientId</c>, tokens are acquired via the IMDS endpoint as the configured managed identity instead of via the app-credentials flow.</param> |
| 25 | internal sealed class BotAuthenticationHandler( |
| 26 | IAuthorizationHeaderProvider authorizationHeaderProvider, |
| 27 | ILogger<BotAuthenticationHandler> logger, |
| 28 | string? authenticationOptionsName = null, |
| 29 | IOptionsMonitor<ManagedIdentityOptions>? managedIdentityOptions = null) : DelegatingHandler |
| 30 | { |
| 31 | private const string AgenticScope = "https://botapi.skype.com/.default"; |
| 32 | private const string BotAppScope = "https://api.botframework.com/.default"; |
| 33 | |
| 34 | private readonly IAuthorizationHeaderProvider _authorizationHeaderProvider = authorizationHeaderProvider ?? throw new ArgumentNullException(nameof(authorizationHeaderProvider)); |
| 35 | private readonly ILogger<BotAuthenticationHandler> _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| 36 | private readonly IOptionsMonitor<ManagedIdentityOptions>? _managedIdentityOptions = managedIdentityOptions; |
| 37 | private static readonly Action<ILogger, string, Exception?> _logAgenticToken = |
| 38 | LoggerMessage.Define<string>(LogLevel.Debug, new(2), "Acquiring agentic token for AgenticAppId {AgenticAppId}"); |
| 39 | private static readonly Action<ILogger, string, Exception?> _logAppOnlyToken = |
| 40 | LoggerMessage.Define<string>(LogLevel.Debug, new(3), "Acquiring app-only token for scope: {Scope}"); |
| 41 | private static readonly Action<ILogger, string, Exception?> _logTokenClaims = |
| 42 | LoggerMessage.Define<string>(LogLevel.Trace, new(4), "Acquired token claims:{Claims}"); |
| 43 | private static readonly Action<ILogger, string, Exception?> _logInvalidAgenticUserId = |
| 44 | LoggerMessage.Define<string>(LogLevel.Warning, new(5), "Invalid AgenticUserId '{AgenticUserId}'; falling back to app-only token."); |
| 45 | private static readonly Action<ILogger, Exception?> _logTokenParseFailure = |
| 46 | LoggerMessage.Define(LogLevel.Warning, new(6), "Failed to parse JWT token for trace logging."); |
| 47 | |
| 48 | /// <summary> |
| 49 | /// Key used to store the agentic identity in HttpRequestMessage options. |
| 50 | /// </summary> |
| 51 | public static readonly HttpRequestOptionsKey<AgenticIdentity?> AgenticIdentityKey = new("AgenticIdentity"); |
| 52 | |
| 53 | /// <inheritdoc/> |
| 54 | protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
| 55 | { |
| 56 | request.Options.TryGetValue(AgenticIdentityKey, out AgenticIdentity? agenticIdentity); |
| 57 | |
| 58 | string token = await GetAuthorizationHeaderAsync(agenticIdentity, cancellationToken).ConfigureAwait(false); |
| 59 | |
| 60 | string tokenValue = token.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) |
| 61 | ? token["Bearer ".Length..] |
| 62 | : token; |
| 63 | |
| 64 | LogTokenClaims(tokenValue); |
| 65 | |
| 66 | request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenValue); |
| 67 | |
| 68 | return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); |
| 69 | } |
| 70 | |
| 71 | /// <summary> |
| 72 | /// Gets an authorization header for Bot Framework API calls. |
| 73 | /// Supports both app-only and agentic (user-delegated) token acquisition. |
| 74 | /// </summary> |
| 75 | /// <param name="agenticIdentity">Optional agentic identity for user-delegated token acquisition. If not provided, acquires an app-only token.</param> |
| 76 | /// <param name="cancellationToken">Cancellation token.</param> |
| 77 | /// <returns>The authorization header value.</returns> |
| 78 | private async Task<string> GetAuthorizationHeaderAsync(AgenticIdentity? agenticIdentity, CancellationToken cancellationToken) |
| 79 | { |
| 80 | string optionsName = authenticationOptionsName ?? BotConfig.DefaultSectionName; |
| 81 | AuthorizationHeaderProviderOptions options = new() |
| 82 | { |
| 83 | AcquireTokenOptions = new AcquireTokenOptions() |
| 84 | { |
| 85 | AuthenticationOptionsName = optionsName, |
| 86 | } |
| 87 | }; |
| 88 | |
| 89 | if (_managedIdentityOptions?.Get(optionsName) is { UserAssignedClientId.Length: > 0 } miOptions) |
| 90 | { |
| 91 | options.AcquireTokenOptions.ManagedIdentity = miOptions; |
| 92 | } |
| 93 | |
| 94 | if (agenticIdentity is not null && |
| 95 | !string.IsNullOrEmpty(agenticIdentity.AgenticAppId) && |
| 96 | !string.IsNullOrEmpty(agenticIdentity.AgenticUserId)) |
| 97 | { |
| 98 | _logAgenticToken(_logger, agenticIdentity.AgenticAppId, null); |
| 99 | |
| 100 | if (!Guid.TryParse(agenticIdentity.AgenticUserId, out Guid agenticUserGuid)) |
| 101 | { |
| 102 | _logInvalidAgenticUserId(_logger, agenticIdentity.AgenticUserId, null); |
| 103 | } |
| 104 | else |
| 105 | { |
| 106 | options.WithAgentUserIdentity(agenticIdentity.AgenticAppId, agenticUserGuid); |
| 107 | string token = await _authorizationHeaderProvider.CreateAuthorizationHeaderAsync([AgenticScope], options, null, cancellationToken).ConfigureAwait(false); |
| 108 | return token; |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | _logAppOnlyToken(_logger, BotAppScope, null); |
| 113 | string appToken = await _authorizationHeaderProvider.CreateAuthorizationHeaderForAppAsync(BotAppScope, options, cancellationToken).ConfigureAwait(false); |
| 114 | |
| 115 | |
| 116 | return appToken; |
| 117 | } |
| 118 | |
| 119 | private void LogTokenClaims(string token) |
| 120 | { |
| 121 | if (!_logger.IsEnabled(LogLevel.Trace)) |
| 122 | { |
| 123 | return; |
| 124 | } |
| 125 | |
| 126 | |
| 127 | try |
| 128 | { |
| 129 | JwtSecurityToken jwtToken = new(token); |
| 130 | string claims = Environment.NewLine + string.Join(Environment.NewLine, jwtToken.Claims.Select(c => $" {c.Type}: {c.Value}")); |
| 131 | _logTokenClaims(_logger, claims, null); |
| 132 | } |
| 133 | catch (ArgumentException ex) |
| 134 | { |
| 135 | _logTokenParseFailure(_logger, ex); |
| 136 | } |
| 137 | } |
| 138 | } |
| 139 | |