microsoft/teams.net

Public

mirrored fromhttps://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
next/core-claude-agents

Branches

Tags

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

Clone

HTTPS

Download ZIP

core/samples/PABot/RoutedTokenAcquisitionService.cs

127lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4using Microsoft.Extensions.Options;
5using Microsoft.Identity.Abstractions;
6using Microsoft.Identity.Web;
7using Microsoft.Teams.Bot.Core.Schema;
8
9namespace PABot
10{
11 /// <summary>
12 /// Token acquisition service that routes to either bot or agentic credentials based on context.
13 /// </summary>
14 public interface IRoutedTokenAcquisitionService
15 {
16 /// <summary>
17 /// Acquires a token using bot (channel) credentials.
18 /// </summary>
19 /// <param name="scope">The scope for the token request.</param>
20 /// <param name="cancellationToken">Cancellation token.</param>
21 /// <returns>An access token.</returns>
22 Task<string> AcquireTokenForBotAsync(string scope, CancellationToken cancellationToken = default);
23
24 /// <summary>
25 /// Acquires a token using agentic application credentials.
26 /// </summary>
27 /// <param name="agenticIdentity">The agentic identity containing AgenticAppId and AgenticUserId.</param>
28 /// <param name="scope">The scope for the token request.</param>
29 /// <param name="cancellationToken">Cancellation token.</param>
30 /// <returns>An access token.</returns>
31 Task<string> AcquireTokenForAgenticAsync(AgenticIdentity agenticIdentity, string scope, CancellationToken cancellationToken = default);
32 }
33
34 /// <summary>
35 /// Implementation of routed token acquisition service for a specific keyed adapter.
36 /// </summary>
37 public class RoutedTokenAcquisitionService : IRoutedTokenAcquisitionService
38 {
39 private readonly bool _hasBotIdentity;
40 private readonly bool _hasAgentIdentity;
41 private readonly IAuthorizationHeaderProvider _authorizationHeaderProvider;
42 private readonly ILogger<RoutedTokenAcquisitionService> _logger;
43
44 public RoutedTokenAcquisitionService(
45 bool hasBotIdentity,
46 bool hasAgentIdentity,
47 IAuthorizationHeaderProvider authorizationHeaderProvider,
48 ILogger<RoutedTokenAcquisitionService> logger)
49 {
50 _hasBotIdentity = hasBotIdentity;
51 _hasAgentIdentity = hasAgentIdentity;
52 _authorizationHeaderProvider = authorizationHeaderProvider;
53 _logger = logger;
54 }
55
56 public async Task<string> AcquireTokenForBotAsync(string scope, CancellationToken cancellationToken = default)
57 {
58 if (!_hasBotIdentity)
59 {
60 throw new InvalidOperationException(
61 "Bot identity (MsalBot) is not configured. Cannot acquire token using bot credentials. " +
62 "Either configure MsalBot section in configuration or use AcquireTokenForAgenticAsync instead.");
63 }
64
65 _logger.LogDebug("Acquiring token for bot credentials using MsalBot configuration");
66
67 // Use the bot client credentials configuration
68 return await _authorizationHeaderProvider.CreateAuthorizationHeaderForAppAsync(
69 scope,
70 new AuthorizationHeaderProviderOptions
71 {
72 AcquireTokenOptions = new AcquireTokenOptions
73 {
74 AuthenticationOptionsName = "MsalBot"
75 }
76 },
77 cancellationToken);
78 }
79
80 public async Task<string> AcquireTokenForAgenticAsync(AgenticIdentity agenticIdentity, string scope, CancellationToken cancellationToken = default)
81 {
82 if (agenticIdentity is null)
83 {
84 throw new ArgumentNullException(nameof(agenticIdentity));
85 }
86
87 if (string.IsNullOrEmpty(agenticIdentity.AgenticAppId))
88 {
89 throw new ArgumentException("AgenticAppId cannot be null or empty", nameof(agenticIdentity));
90 }
91
92 if (string.IsNullOrEmpty(agenticIdentity.AgenticUserId))
93 {
94 throw new ArgumentException("AgenticUserId cannot be null or empty", nameof(agenticIdentity));
95 }
96
97 if (!_hasAgentIdentity)
98 {
99 throw new InvalidOperationException(
100 "Agent identity (MsalAgent) is not configured. Cannot acquire token using agent credentials. " +
101 "Configure MsalAgent section in configuration to use agentic authentication.");
102 }
103
104 _logger.LogDebug("Acquiring token for agentic credentials with AppId '{AppId}' and UserId '{UserId}'",
105 agenticIdentity.AgenticAppId,
106 agenticIdentity.AgenticUserId);
107
108 // Use the agentic client credentials configuration
109 AuthorizationHeaderProviderOptions options = new()
110 {
111 AcquireTokenOptions = new AcquireTokenOptions
112 {
113 AuthenticationOptionsName = "MsalAgent"
114 }
115 };
116
117 // Use WithAgentUserIdentity to acquire token with agentic identity
118 options.WithAgentUserIdentity(agenticIdentity.AgenticAppId, Guid.Parse(agenticIdentity.AgenticUserId));
119
120 return await _authorizationHeaderProvider.CreateAuthorizationHeaderAsync(
121 [scope],
122 options,
123 null,
124 cancellationToken);
125 }
126 }
127}
128