microsoft/teams.net
Publicmirrored from https://github.com/microsoft/teams.netAvailable
core/src/Microsoft.Teams.Core/Hosting/BotAuthenticationHandler.cs
144lines · 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="scope">The scope for the token request.</param> |
| 24 | /// <param name="managedIdentityOptions">Optional managed identity options for user-assigned managed identity authentication.</param> |
| 25 | /// <param name="authenticationOptionsName">The name of the MSAL configuration options to use for token acquisition. Defaults to <see cref="MsalConfigurationExtensions.MsalConfigKey"/>.</param> |
| 26 | internal sealed class BotAuthenticationHandler( |
| 27 | IAuthorizationHeaderProvider authorizationHeaderProvider, |
| 28 | ILogger<BotAuthenticationHandler> logger, |
| 29 | string scope, |
| 30 | IOptions<ManagedIdentityOptions>? managedIdentityOptions = null, |
| 31 | string? authenticationOptionsName = null) : DelegatingHandler |
| 32 | { |
| 33 | private readonly IAuthorizationHeaderProvider _authorizationHeaderProvider = authorizationHeaderProvider ?? throw new ArgumentNullException(nameof(authorizationHeaderProvider)); |
| 34 | private readonly ILogger<BotAuthenticationHandler> _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| 35 | private readonly string _scope = scope ?? throw new ArgumentNullException(nameof(scope)); |
| 36 | private readonly IOptions<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 | AuthorizationHeaderProviderOptions options = new() |
| 81 | { |
| 82 | AcquireTokenOptions = new AcquireTokenOptions() |
| 83 | { |
| 84 | AuthenticationOptionsName = authenticationOptionsName ?? MsalConfigurationExtensions.MsalConfigKey, |
| 85 | } |
| 86 | }; |
| 87 | |
| 88 | // Conditionally apply ManagedIdentity configuration if registered |
| 89 | if (_managedIdentityOptions is not null) |
| 90 | { |
| 91 | ManagedIdentityOptions miOptions = _managedIdentityOptions.Value; |
| 92 | |
| 93 | if (!string.IsNullOrEmpty(miOptions.UserAssignedClientId)) |
| 94 | { |
| 95 | _logger.ApplyingManagedIdentity(miOptions.UserAssignedClientId); |
| 96 | options.AcquireTokenOptions.ManagedIdentity = miOptions; |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | if (agenticIdentity is not null && |
| 101 | !string.IsNullOrEmpty(agenticIdentity.AgenticAppId) && |
| 102 | !string.IsNullOrEmpty(agenticIdentity.AgenticUserId)) |
| 103 | { |
| 104 | _logAgenticToken(_logger, agenticIdentity.AgenticAppId, null); |
| 105 | |
| 106 | if (!Guid.TryParse(agenticIdentity.AgenticUserId, out Guid agenticUserGuid)) |
| 107 | { |
| 108 | _logInvalidAgenticUserId(_logger, agenticIdentity.AgenticUserId, null); |
| 109 | } |
| 110 | else |
| 111 | { |
| 112 | options.WithAgentUserIdentity(agenticIdentity.AgenticAppId, agenticUserGuid); |
| 113 | string token = await _authorizationHeaderProvider.CreateAuthorizationHeaderAsync([_scope], options, null, cancellationToken).ConfigureAwait(false); |
| 114 | return token; |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | _logAppOnlyToken(_logger, _scope, null); |
| 119 | string appToken = await _authorizationHeaderProvider.CreateAuthorizationHeaderForAppAsync(_scope, options, cancellationToken).ConfigureAwait(false); |
| 120 | |
| 121 | |
| 122 | return appToken; |
| 123 | } |
| 124 | |
| 125 | private void LogTokenClaims(string token) |
| 126 | { |
| 127 | if (!_logger.IsEnabled(LogLevel.Trace)) |
| 128 | { |
| 129 | return; |
| 130 | } |
| 131 | |
| 132 | |
| 133 | try |
| 134 | { |
| 135 | JwtSecurityToken jwtToken = new(token); |
| 136 | string claims = Environment.NewLine + string.Join(Environment.NewLine, jwtToken.Claims.Select(c => $" {c.Type}: {c.Value}")); |
| 137 | _logTokenClaims(_logger, claims, null); |
| 138 | } |
| 139 | catch (ArgumentException ex) |
| 140 | { |
| 141 | _logTokenParseFailure(_logger, ex); |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |