microsoft/teams.net

Public

mirrored from https://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
c92c1919ec3b5a0b25a067ad4ad46da598a2fdca

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

core/src/Microsoft.Teams.Bot.Core/Hosting/BotAuthenticationHandler.cs

103lines · modecode

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