microsoft/teams.net
Publicmirrored from https://github.com/microsoft/teams.netAvailable
core/src/Microsoft.Bot.Core/Hosting/BotAuthenticationHandler.cs
104lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | using System.Net.Http.Headers; |
| 5 | |
| 6 | using Microsoft.Bot.Core.Schema; |
| 7 | using Microsoft.Extensions.Logging; |
| 8 | using Microsoft.Extensions.Options; |
| 9 | using Microsoft.Identity.Abstractions; |
| 10 | using Microsoft.Identity.Web; |
| 11 | |
| 12 | namespace Microsoft.Bot.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 | internal sealed class BotAuthenticationHandler( |
| 26 | IAuthorizationHeaderProvider authorizationHeaderProvider, |
| 27 | ILogger<BotAuthenticationHandler> logger, |
| 28 | string scope, |
| 29 | IOptions<ManagedIdentityOptions>? managedIdentityOptions = null) : DelegatingHandler |
| 30 | { |
| 31 | private readonly IAuthorizationHeaderProvider _authorizationHeaderProvider = authorizationHeaderProvider ?? throw new ArgumentNullException(nameof(authorizationHeaderProvider)); |
| 32 | private readonly ILogger<BotAuthenticationHandler> _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| 33 | private readonly string _scope = scope ?? throw new ArgumentNullException(nameof(scope)); |
| 34 | private readonly IOptions<ManagedIdentityOptions>? _managedIdentityOptions = managedIdentityOptions; |
| 35 | private static readonly Action<ILogger, string, Exception?> _logAgenticToken = |
| 36 | LoggerMessage.Define<string>(LogLevel.Debug, new(2), "Acquiring agentic token for app {AgenticAppId}"); |
| 37 | private static readonly Action<ILogger, string, Exception?> _logAppOnlyToken = |
| 38 | LoggerMessage.Define<string>(LogLevel.Debug, new(3), "Acquiring app-only token for scope: {Scope}"); |
| 39 | |
| 40 | /// <summary> |
| 41 | /// Key used to store the agentic identity in HttpRequestMessage options. |
| 42 | /// </summary> |
| 43 | public static readonly HttpRequestOptionsKey<AgenticIdentity?> AgenticIdentityKey = new("AgenticIdentity"); |
| 44 | |
| 45 | /// <inheritdoc/> |
| 46 | protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
| 47 | { |
| 48 | request.Options.TryGetValue(AgenticIdentityKey, out AgenticIdentity? agenticIdentity); |
| 49 | |
| 50 | string token = await GetAuthorizationHeaderAsync(agenticIdentity, cancellationToken).ConfigureAwait(false); |
| 51 | |
| 52 | string tokenValue = token.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) |
| 53 | ? token["Bearer ".Length..] |
| 54 | : token; |
| 55 | |
| 56 | request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenValue); |
| 57 | |
| 58 | return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); |
| 59 | } |
| 60 | |
| 61 | /// <summary> |
| 62 | /// Gets an authorization header for Bot Framework API calls. |
| 63 | /// Supports both app-only and agentic (user-delegated) token acquisition. |
| 64 | /// </summary> |
| 65 | /// <param name="agenticIdentity">Optional agentic identity for user-delegated token acquisition. If not provided, acquires an app-only token.</param> |
| 66 | /// <param name="cancellationToken">Cancellation token.</param> |
| 67 | /// <returns>The authorization header value.</returns> |
| 68 | private async Task<string> GetAuthorizationHeaderAsync(AgenticIdentity? agenticIdentity, CancellationToken cancellationToken) |
| 69 | { |
| 70 | AuthorizationHeaderProviderOptions options = new() |
| 71 | { |
| 72 | AcquireTokenOptions = new AcquireTokenOptions() |
| 73 | { |
| 74 | //AuthenticationOptionsName = _aadConfigSectionName, |
| 75 | } |
| 76 | }; |
| 77 | |
| 78 | // Conditionally apply ManagedIdentity configuration if registered |
| 79 | if (_managedIdentityOptions is not null) |
| 80 | { |
| 81 | var miOptions = _managedIdentityOptions.Value; |
| 82 | |
| 83 | if (!string.IsNullOrEmpty(miOptions.UserAssignedClientId)) |
| 84 | { |
| 85 | options.AcquireTokenOptions.ManagedIdentity = miOptions; |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | if (agenticIdentity is not null && |
| 90 | !string.IsNullOrEmpty(agenticIdentity.AgenticAppId) && |
| 91 | !string.IsNullOrEmpty(agenticIdentity.AgenticUserId)) |
| 92 | { |
| 93 | _logAgenticToken(_logger, agenticIdentity.AgenticAppId, null); |
| 94 | |
| 95 | options.WithAgentUserIdentity(agenticIdentity.AgenticAppId, Guid.Parse(agenticIdentity.AgenticUserId)); |
| 96 | string token = await _authorizationHeaderProvider.CreateAuthorizationHeaderAsync([_scope], options, null, cancellationToken).ConfigureAwait(false); |
| 97 | return token; |
| 98 | } |
| 99 | |
| 100 | _logAppOnlyToken(_logger, _scope, null); |
| 101 | string appToken = await _authorizationHeaderProvider.CreateAuthorizationHeaderForAppAsync(_scope, options, cancellationToken).ConfigureAwait(false); |
| 102 | return appToken; |
| 103 | } |
| 104 | } |
| 105 | |