microsoft-agents-authentication-msal 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ from .msal_auth import MsalAuth
2
+ from .msal_connection_manager import MsalConnectionManager
3
+
4
+ __all__ = [
5
+ "MsalAuth",
6
+ "MsalConnectionManager",
7
+ ]
@@ -0,0 +1,15 @@
1
+ # Copyright (c) Microsoft Corporation. All rights reserved.
2
+ # Licensed under the MIT License.
3
+
4
+ """
5
+ Error resources for Microsoft Agents Authentication MSAL package.
6
+ """
7
+
8
+ from microsoft_agents.activity.errors import ErrorMessage
9
+
10
+ from .error_resources import AuthenticationErrorResources
11
+
12
+ # Singleton instance
13
+ authentication_errors = AuthenticationErrorResources()
14
+
15
+ __all__ = ["ErrorMessage", "AuthenticationErrorResources", "authentication_errors"]
@@ -0,0 +1,67 @@
1
+ # Copyright (c) Microsoft Corporation. All rights reserved.
2
+ # Licensed under the MIT License.
3
+
4
+ """
5
+ Authentication error resources for Microsoft Agents SDK.
6
+
7
+ Error codes are in the range -60000 to -60999.
8
+ """
9
+
10
+ from microsoft_agents.activity.errors import ErrorMessage
11
+
12
+
13
+ class AuthenticationErrorResources:
14
+ """
15
+ Error messages for authentication operations.
16
+
17
+ Error codes are organized in the range -60000 to -60999.
18
+ """
19
+
20
+ FailedToAcquireToken = ErrorMessage(
21
+ "Failed to acquire token. {0}",
22
+ -60012,
23
+ )
24
+
25
+ InvalidInstanceUrl = ErrorMessage(
26
+ "Invalid instance URL",
27
+ -60013,
28
+ )
29
+
30
+ OnBehalfOfFlowNotSupportedManagedIdentity = ErrorMessage(
31
+ "On-behalf-of flow is not supported with Managed Identity authentication.",
32
+ -60014,
33
+ )
34
+
35
+ OnBehalfOfFlowNotSupportedAuthType = ErrorMessage(
36
+ "On-behalf-of flow is not supported with the current authentication type: {0}",
37
+ -60015,
38
+ )
39
+
40
+ AuthenticationTypeNotSupported = ErrorMessage(
41
+ "Authentication type not supported",
42
+ -60016,
43
+ )
44
+
45
+ AgentApplicationInstanceIdRequired = ErrorMessage(
46
+ "Agent application instance Id must be provided.",
47
+ -60017,
48
+ )
49
+
50
+ FailedToAcquireAgenticInstanceToken = ErrorMessage(
51
+ "Failed to acquire agentic instance token or agent token for agent_app_instance_id {0}",
52
+ -60018,
53
+ )
54
+
55
+ AgentApplicationInstanceIdAndUserIdRequired = ErrorMessage(
56
+ "Agent application instance Id and agentic user Id must be provided.",
57
+ -60019,
58
+ )
59
+
60
+ FailedToAcquireInstanceOrAgentToken = ErrorMessage(
61
+ "Failed to acquire instance token or agent token for agent_app_instance_id {0} and agentic_user_id {1}",
62
+ -60020,
63
+ )
64
+
65
+ def __init__(self):
66
+ """Initialize AuthenticationErrorResources."""
67
+ pass
@@ -0,0 +1,442 @@
1
+ # Copyright (c) Microsoft Corporation. All rights reserved.
2
+ # Licensed under the MIT License.
3
+
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import logging
8
+ import jwt
9
+ from typing import Optional
10
+ from urllib.parse import urlparse, ParseResult as URI
11
+ from msal import (
12
+ ConfidentialClientApplication,
13
+ ManagedIdentityClient,
14
+ UserAssignedManagedIdentity,
15
+ SystemAssignedManagedIdentity,
16
+ )
17
+ from requests import Session
18
+ from cryptography.x509 import load_pem_x509_certificate
19
+ from cryptography.hazmat.backends import default_backend
20
+ from cryptography.hazmat.primitives import hashes
21
+
22
+ from microsoft_agents.activity._utils import _DeferredString
23
+
24
+ from microsoft_agents.hosting.core import (
25
+ AuthTypes,
26
+ AccessTokenProviderBase,
27
+ AgentAuthConfiguration,
28
+ )
29
+ from microsoft_agents.authentication.msal.errors import authentication_errors
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+
34
+ async def _async_acquire_token_for_client(msal_auth_client, *args, **kwargs):
35
+ """MSAL in Python does not support async, so we use asyncio.to_thread to run it in
36
+ a separate thread and avoid blocking the event loop
37
+ """
38
+ return await asyncio.to_thread(
39
+ lambda: msal_auth_client.acquire_token_for_client(*args, **kwargs)
40
+ )
41
+
42
+
43
+ class MsalAuth(AccessTokenProviderBase):
44
+
45
+ _client_credential_cache = None
46
+
47
+ def __init__(self, msal_configuration: AgentAuthConfiguration):
48
+ """Initializes the MsalAuth class with the given configuration.
49
+
50
+ :param msal_configuration: The MSAL authentication configuration. Assumed to
51
+ not be mutated after being passed in.
52
+ :type msal_configuration: :class:`microsoft_agents.hosting.core.authorization.agent_auth_configuration.AgentAuthConfiguration`
53
+ """
54
+
55
+ self._msal_configuration = msal_configuration
56
+ self._msal_auth_client = None
57
+ logger.debug(
58
+ f"Initializing MsalAuth with configuration: {self._msal_configuration}"
59
+ )
60
+
61
+ async def get_access_token(
62
+ self, resource_url: str, scopes: list[str], force_refresh: bool = False
63
+ ) -> str:
64
+ logger.debug(
65
+ f"Requesting access token for resource: {resource_url}, scopes: {scopes}"
66
+ )
67
+ valid_uri, instance_uri = self._uri_validator(resource_url)
68
+ if not valid_uri:
69
+ raise ValueError(str(authentication_errors.InvalidInstanceUrl))
70
+
71
+ local_scopes = self._resolve_scopes_list(instance_uri, scopes)
72
+ self._create_client_application()
73
+
74
+ if isinstance(self._msal_auth_client, ManagedIdentityClient):
75
+ logger.info("Acquiring token using Managed Identity Client.")
76
+ auth_result_payload = await _async_acquire_token_for_client(
77
+ self._msal_auth_client, resource=resource_url
78
+ )
79
+ elif isinstance(self._msal_auth_client, ConfidentialClientApplication):
80
+ logger.info("Acquiring token using Confidential Client Application.")
81
+ auth_result_payload = await _async_acquire_token_for_client(
82
+ self._msal_auth_client, scopes=local_scopes
83
+ )
84
+ else:
85
+ auth_result_payload = None
86
+
87
+ res = auth_result_payload.get("access_token") if auth_result_payload else None
88
+ if not res:
89
+ logger.error("Failed to acquire token for resource %s", auth_result_payload)
90
+ raise ValueError(
91
+ authentication_errors.FailedToAcquireToken.format(
92
+ str(auth_result_payload)
93
+ )
94
+ )
95
+
96
+ return res
97
+
98
+ async def acquire_token_on_behalf_of(
99
+ self, scopes: list[str], user_assertion: str
100
+ ) -> str:
101
+ """
102
+ Acquire a token on behalf of a user.
103
+ :param scopes: The scopes for which to get the token.
104
+ :param user_assertion: The user assertion token.
105
+ :return: The access token as a string.
106
+ """
107
+
108
+ self._create_client_application()
109
+ if isinstance(self._msal_auth_client, ManagedIdentityClient):
110
+ logger.error(
111
+ "Attempted on-behalf-of flow with Managed Identity authentication."
112
+ )
113
+ raise NotImplementedError(
114
+ str(authentication_errors.OnBehalfOfFlowNotSupportedManagedIdentity)
115
+ )
116
+ elif isinstance(self._msal_auth_client, ConfidentialClientApplication):
117
+ # TODO: Handling token error / acquisition failed
118
+
119
+ # MSAL in Python does not support async, so we use asyncio.to_thread to run it in
120
+ # a separate thread and avoid blocking the event loop
121
+ token = await asyncio.to_thread(
122
+ lambda: self._msal_auth_client.acquire_token_on_behalf_of(
123
+ scopes=scopes, user_assertion=user_assertion
124
+ )
125
+ )
126
+
127
+ if "access_token" not in token:
128
+ logger.error(
129
+ f"Failed to acquire token on behalf of user: {user_assertion}"
130
+ )
131
+ raise ValueError(
132
+ authentication_errors.FailedToAcquireToken.format(str(token))
133
+ )
134
+
135
+ return token["access_token"]
136
+
137
+ logger.error(
138
+ f"On-behalf-of flow is not supported with the current authentication type: {self._msal_auth_client.__class__.__name__}"
139
+ )
140
+ raise NotImplementedError(
141
+ authentication_errors.OnBehalfOfFlowNotSupportedAuthType.format(
142
+ self._msal_auth_client.__class__.__name__
143
+ )
144
+ )
145
+
146
+ def _create_client_application(self) -> None:
147
+
148
+ if self._msal_auth_client:
149
+ return
150
+
151
+ if self._msal_configuration.AUTH_TYPE == AuthTypes.user_managed_identity:
152
+ self._msal_auth_client = ManagedIdentityClient(
153
+ UserAssignedManagedIdentity(
154
+ client_id=self._msal_configuration.CLIENT_ID
155
+ ),
156
+ http_client=Session(),
157
+ )
158
+
159
+ elif self._msal_configuration.AUTH_TYPE == AuthTypes.system_managed_identity:
160
+ self._msal_auth_client = ManagedIdentityClient(
161
+ SystemAssignedManagedIdentity(),
162
+ http_client=Session(),
163
+ )
164
+ else:
165
+ authority_path = self._msal_configuration.TENANT_ID or "botframework.com"
166
+ authority = f"https://login.microsoftonline.com/{authority_path}"
167
+
168
+ if self._client_credential_cache:
169
+ logger.info("Using cached client credentials for MSAL authentication.")
170
+ pass
171
+ elif self._msal_configuration.AUTH_TYPE == AuthTypes.client_secret:
172
+ self._client_credential_cache = self._msal_configuration.CLIENT_SECRET
173
+ elif self._msal_configuration.AUTH_TYPE == AuthTypes.certificate:
174
+ with open(self._msal_configuration.CERT_KEY_FILE) as file:
175
+ logger.info(
176
+ "Loading certificate private key for MSAL authentication."
177
+ )
178
+ private_key = file.read()
179
+
180
+ with open(self._msal_configuration.CERT_PEM_FILE) as file:
181
+ logger.info("Loading public certificate for MSAL authentication.")
182
+ public_certificate = file.read()
183
+
184
+ # Create an X509 object and calculate the thumbprint
185
+ logger.info("Calculating thumbprint for the public certificate.")
186
+ cert = load_pem_x509_certificate(
187
+ data=bytes(public_certificate, "UTF-8"), backend=default_backend()
188
+ )
189
+ thumbprint = cert.fingerprint(hashes.SHA1()).hex()
190
+
191
+ self._client_credential_cache = {
192
+ "thumbprint": thumbprint,
193
+ "private_key": private_key,
194
+ }
195
+ else:
196
+ logger.error(
197
+ f"Unsupported authentication type: {self._msal_configuration.AUTH_TYPE}"
198
+ )
199
+ raise NotImplementedError(
200
+ str(authentication_errors.AuthenticationTypeNotSupported)
201
+ )
202
+
203
+ self._msal_auth_client = ConfidentialClientApplication(
204
+ client_id=self._msal_configuration.CLIENT_ID,
205
+ authority=authority,
206
+ client_credential=self._client_credential_cache,
207
+ )
208
+
209
+ @staticmethod
210
+ def _uri_validator(url_str: str) -> tuple[bool, Optional[URI]]:
211
+ try:
212
+ result = urlparse(url_str)
213
+ return all([result.scheme, result.netloc]), result
214
+ except AttributeError:
215
+ logger.error(f"URI parsing error for {url_str}")
216
+ return False, None
217
+
218
+ def _resolve_scopes_list(self, instance_url: URI, scopes=None) -> list[str]:
219
+ if scopes:
220
+ return scopes
221
+
222
+ temp_list: list[str] = []
223
+ for scope in self._msal_configuration.SCOPES:
224
+ scope_placeholder = scope
225
+ if "{instance}" in scope_placeholder.lower():
226
+ scope_placeholder = scope_placeholder.replace(
227
+ "{instance}", f"{instance_url.scheme}://{instance_url.hostname}"
228
+ )
229
+ temp_list.append(scope_placeholder)
230
+ logger.debug(f"Resolved scopes: {temp_list}")
231
+ return temp_list
232
+
233
+ # the call to MSAL is blocking, but in the future we want to create an asyncio task
234
+ # to avoid this
235
+ async def get_agentic_application_token(
236
+ self, agent_app_instance_id: str
237
+ ) -> Optional[str]:
238
+ """Gets the agentic application token for the given agent application instance ID.
239
+
240
+ :param agent_app_instance_id: The agent application instance ID.
241
+ :type agent_app_instance_id: str
242
+ :return: The agentic application token, or None if not found.
243
+ :rtype: Optional[str]
244
+ """
245
+
246
+ if not agent_app_instance_id:
247
+ raise ValueError(
248
+ str(authentication_errors.AgentApplicationInstanceIdRequired)
249
+ )
250
+
251
+ logger.info(
252
+ "Attempting to get agentic application token from agent_app_instance_id %s",
253
+ agent_app_instance_id,
254
+ )
255
+ self._create_client_application()
256
+
257
+ if isinstance(self._msal_auth_client, ConfidentialClientApplication):
258
+
259
+ # https://github.dev/AzureAD/microsoft-authentication-library-for-dotnet
260
+ auth_result_payload = await _async_acquire_token_for_client(
261
+ self._msal_auth_client,
262
+ ["api://AzureAdTokenExchange/.default"],
263
+ data={"fmi_path": agent_app_instance_id},
264
+ )
265
+
266
+ if auth_result_payload:
267
+ return auth_result_payload.get("access_token")
268
+
269
+ return None
270
+
271
+ async def get_agentic_instance_token(
272
+ self, agent_app_instance_id: str
273
+ ) -> tuple[str, str]:
274
+ """Gets the agentic instance token for the given agent application instance ID.
275
+
276
+ :param agent_app_instance_id: The agent application instance ID.
277
+ :type agent_app_instance_id: str
278
+ :return: A tuple containing the agentic instance token and the agent application token.
279
+ :rtype: tuple[str, str]
280
+ """
281
+
282
+ if not agent_app_instance_id:
283
+ raise ValueError(
284
+ str(authentication_errors.AgentApplicationInstanceIdRequired)
285
+ )
286
+
287
+ logger.info(
288
+ "Attempting to get agentic instance token from agent_app_instance_id %s",
289
+ agent_app_instance_id,
290
+ )
291
+ agent_token_result = await self.get_agentic_application_token(
292
+ agent_app_instance_id
293
+ )
294
+
295
+ if not agent_token_result:
296
+ logger.error(
297
+ "Failed to acquire agentic instance token or agent token for agent_app_instance_id %s",
298
+ agent_app_instance_id,
299
+ )
300
+ raise Exception(
301
+ authentication_errors.FailedToAcquireAgenticInstanceToken.format(
302
+ agent_app_instance_id
303
+ )
304
+ )
305
+
306
+ authority = (
307
+ f"https://login.microsoftonline.com/{self._msal_configuration.TENANT_ID}"
308
+ )
309
+
310
+ instance_app = ConfidentialClientApplication(
311
+ client_id=agent_app_instance_id,
312
+ authority=authority,
313
+ client_credential={"client_assertion": agent_token_result},
314
+ )
315
+
316
+ agentic_instance_token = await _async_acquire_token_for_client(
317
+ instance_app, ["api://AzureAdTokenExchange/.default"]
318
+ )
319
+
320
+ if not agentic_instance_token:
321
+ logger.error(
322
+ "Failed to acquire agentic instance token or agent token for agent_app_instance_id %s",
323
+ agent_app_instance_id,
324
+ )
325
+ raise Exception(
326
+ authentication_errors.FailedToAcquireAgenticInstanceToken.format(
327
+ agent_app_instance_id
328
+ )
329
+ )
330
+
331
+ # future scenario where we don't know the blueprint id upfront
332
+
333
+ token = agentic_instance_token.get("access_token")
334
+ if not token:
335
+ logger.error(
336
+ "Failed to acquire agentic instance token, %s", agentic_instance_token
337
+ )
338
+ raise ValueError(
339
+ authentication_errors.FailedToAcquireToken.format(
340
+ str(agentic_instance_token)
341
+ )
342
+ )
343
+
344
+ logger.debug(
345
+ "Agentic blueprint id: %s",
346
+ _DeferredString(
347
+ lambda: jwt.decode(token, options={"verify_signature": False}).get(
348
+ "xms_par_app_azp"
349
+ )
350
+ ),
351
+ )
352
+
353
+ return agentic_instance_token["access_token"], agent_token_result
354
+
355
+ async def get_agentic_user_token(
356
+ self, agent_app_instance_id: str, agentic_user_id: str, scopes: list[str]
357
+ ) -> Optional[str]:
358
+ """Gets the agentic user token for the given agent application instance ID and agentic user Id and the scopes.
359
+
360
+ :param agent_app_instance_id: The agent application instance ID.
361
+ :type agent_app_instance_id: str
362
+ :param agentic_user_id: The agentic user ID.
363
+ :type agentic_user_id: str
364
+ :param scopes: The scopes to request for the token.
365
+ :type scopes: list[str]
366
+ :return: The agentic user token, or None if not found.
367
+ :rtype: Optional[str]
368
+ """
369
+ if not agent_app_instance_id or not agentic_user_id:
370
+ raise ValueError(
371
+ str(authentication_errors.AgentApplicationInstanceIdAndUserIdRequired)
372
+ )
373
+
374
+ logger.info(
375
+ "Attempting to get agentic user token from agent_app_instance_id %s and agentic_user_id %s",
376
+ agent_app_instance_id,
377
+ agentic_user_id,
378
+ )
379
+ instance_token, agent_token = await self.get_agentic_instance_token(
380
+ agent_app_instance_id
381
+ )
382
+
383
+ if not instance_token or not agent_token:
384
+ logger.error(
385
+ "Failed to acquire instance token or agent token for agent_app_instance_id %s and agentic_user_id %s",
386
+ agent_app_instance_id,
387
+ agentic_user_id,
388
+ )
389
+ raise Exception(
390
+ authentication_errors.FailedToAcquireInstanceOrAgentToken.format(
391
+ agent_app_instance_id, agentic_user_id
392
+ )
393
+ )
394
+
395
+ authority = (
396
+ f"https://login.microsoftonline.com/{self._msal_configuration.TENANT_ID}"
397
+ )
398
+
399
+ instance_app = ConfidentialClientApplication(
400
+ client_id=agent_app_instance_id,
401
+ authority=authority,
402
+ client_credential={"client_assertion": agent_token},
403
+ )
404
+
405
+ logger.info(
406
+ "Acquiring agentic user token for agent_app_instance_id %s and agentic_user_id %s",
407
+ agent_app_instance_id,
408
+ agentic_user_id,
409
+ )
410
+ # MSAL in Python does not support async, so we use asyncio.to_thread to run it in
411
+ # a separate thread and avoid blocking the event loop
412
+ auth_result_payload = await _async_acquire_token_for_client(
413
+ instance_app,
414
+ scopes,
415
+ data={
416
+ "user_id": agentic_user_id,
417
+ "user_federated_identity_credential": instance_token,
418
+ "grant_type": "user_fic",
419
+ },
420
+ )
421
+
422
+ if not auth_result_payload:
423
+ logger.error(
424
+ "Failed to acquire agentic user token for agent_app_instance_id %s and agentic_user_id %s, %s",
425
+ agent_app_instance_id,
426
+ agentic_user_id,
427
+ auth_result_payload,
428
+ )
429
+ return None
430
+
431
+ access_token = auth_result_payload.get("access_token")
432
+ if not access_token:
433
+ logger.error(
434
+ "Failed to acquire agentic user token for agent_app_instance_id %s and agentic_user_id %s, %s",
435
+ agent_app_instance_id,
436
+ agentic_user_id,
437
+ auth_result_payload,
438
+ )
439
+ return None
440
+
441
+ logger.info("Acquired agentic user token response.")
442
+ return access_token
@@ -0,0 +1,140 @@
1
+ # Copyright (c) Microsoft Corporation. All rights reserved.
2
+ # Licensed under the MIT License.
3
+
4
+ import re
5
+ from typing import Dict, List, Optional
6
+ from microsoft_agents.hosting.core import (
7
+ AgentAuthConfiguration,
8
+ AccessTokenProviderBase,
9
+ ClaimsIdentity,
10
+ Connections,
11
+ )
12
+
13
+ from .msal_auth import MsalAuth
14
+
15
+
16
+ class MsalConnectionManager(Connections):
17
+ _connections: Dict[str, MsalAuth]
18
+ _connections_map: List[Dict[str, str]]
19
+ _service_connection_configuration: AgentAuthConfiguration
20
+
21
+ def __init__(
22
+ self,
23
+ connections_configurations: Optional[Dict[str, AgentAuthConfiguration]] = None,
24
+ connections_map: Optional[List[Dict[str, str]]] = None,
25
+ **kwargs,
26
+ ):
27
+ """
28
+ Initialize the MSAL connection manager.
29
+
30
+ :arg connections_configurations: A dictionary of connection configurations.
31
+ :type connections_configurations: Dict[str, :class:`microsoft_agents.hosting.core.AgentAuthConfiguration`]
32
+ :arg connections_map: A list of connection mappings.
33
+ :type connections_map: List[Dict[str, str]]
34
+ :raises ValueError: If no service connection configuration is provided.
35
+ """
36
+
37
+ self._connections: Dict[str, MsalAuth] = {}
38
+ self._connections_map = connections_map or kwargs.get("CONNECTIONSMAP", {})
39
+ self._service_connection_configuration: AgentAuthConfiguration = None
40
+
41
+ if connections_configurations:
42
+ for (
43
+ connection_name,
44
+ connection_settings,
45
+ ) in connections_configurations.items():
46
+ self._connections[connection_name] = MsalAuth(
47
+ AgentAuthConfiguration(**connection_settings)
48
+ )
49
+ else:
50
+ raw_configurations: Dict[str, Dict] = kwargs.get("CONNECTIONS", {})
51
+ for connection_name, connection_settings in raw_configurations.items():
52
+ parsed_configuration = AgentAuthConfiguration(
53
+ **connection_settings.get("SETTINGS", {})
54
+ )
55
+ self._connections[connection_name] = MsalAuth(parsed_configuration)
56
+ if connection_name == "SERVICE_CONNECTION":
57
+ self._service_connection_configuration = parsed_configuration
58
+
59
+ if not self._connections.get("SERVICE_CONNECTION", None):
60
+ raise ValueError("No service connection configuration provided.")
61
+
62
+ def get_connection(self, connection_name: Optional[str]) -> AccessTokenProviderBase:
63
+ """
64
+ Get the OAuth connection for the agent.
65
+
66
+ :arg connection_name: The name of the connection.
67
+ :type connection_name: Optional[str]
68
+ :return: The OAuth connection for the agent.
69
+ :rtype: :class:`microsoft_agents.hosting.core.AccessTokenProviderBase`
70
+ """
71
+ # should never be None
72
+ return self._connections.get(connection_name, None)
73
+
74
+ def get_default_connection(self) -> AccessTokenProviderBase:
75
+ """
76
+ Get the default OAuth connection for the agent.
77
+
78
+ :return: The default OAuth connection for the agent.
79
+ :rtype: :class:`microsoft_agents.hosting.core.AccessTokenProviderBase`
80
+ """
81
+ # should never be None
82
+ return self._connections.get("SERVICE_CONNECTION", None)
83
+
84
+ def get_token_provider(
85
+ self, claims_identity: ClaimsIdentity, service_url: str
86
+ ) -> AccessTokenProviderBase:
87
+ """
88
+ Get the OAuth token provider for the agent.
89
+
90
+ :arg claims_identity: The claims identity of the bot.
91
+ :type claims_identity: :class:`microsoft_agents.hosting.core.ClaimsIdentity`
92
+ :arg service_url: The service URL of the bot.
93
+ :type service_url: str
94
+ :return: The OAuth token provider for the agent.
95
+ :rtype: :class:`microsoft_agents.hosting.core.AccessTokenProviderBase`
96
+ :raises ValueError: If no connection is found for the given audience and service URL.
97
+ """
98
+ if not claims_identity or not service_url:
99
+ raise ValueError(
100
+ "Claims identity and Service URL are required to get the token provider."
101
+ )
102
+
103
+ if not self._connections_map:
104
+ return self.get_default_connection()
105
+
106
+ aud = claims_identity.get_app_id() or ""
107
+ for item in self._connections_map:
108
+ audience_match = True
109
+ item_aud = item.get("AUDIENCE", "")
110
+ if item_aud:
111
+ audience_match = item_aud.lower() == aud.lower()
112
+
113
+ if audience_match:
114
+ item_service_url = item.get("SERVICEURL", "")
115
+ if item_service_url == "*" or item_service_url == "":
116
+ connection_name = item.get("CONNECTION")
117
+ connection = self.get_connection(connection_name)
118
+ if connection:
119
+ return connection
120
+
121
+ else:
122
+ res = re.match(item_service_url, service_url, re.IGNORECASE)
123
+ if res:
124
+ connection_name = item.get("CONNECTION")
125
+ connection = self.get_connection(connection_name)
126
+ if connection:
127
+ return connection
128
+
129
+ raise ValueError(
130
+ f"No connection found for audience '{aud}' and serviceUrl '{service_url}'."
131
+ )
132
+
133
+ def get_default_connection_configuration(self) -> AgentAuthConfiguration:
134
+ """
135
+ Get the default connection configuration for the agent.
136
+
137
+ :return: The default connection configuration for the agent.
138
+ :rtype: :class:`microsoft_agents.hosting.core.AgentAuthConfiguration`
139
+ """
140
+ return self._service_connection_configuration
@@ -0,0 +1,166 @@
1
+ Metadata-Version: 2.4
2
+ Name: microsoft-agents-authentication-msal
3
+ Version: 0.6.1
4
+ Summary: A msal-based authentication library for Microsoft Agents
5
+ Author: Microsoft Corporation
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/microsoft/Agents
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.10
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Operating System :: OS Independent
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: microsoft-agents-hosting-core==0.6.1
19
+ Requires-Dist: msal>=1.31.1
20
+ Requires-Dist: requests>=2.32.3
21
+ Requires-Dist: cryptography>=44.0.0
22
+ Dynamic: license-file
23
+ Dynamic: requires-dist
24
+
25
+ # Microsoft Agents MSAL Authentication
26
+
27
+ [![PyPI version](https://img.shields.io/pypi/v/microsoft-agents-authentication-msal)](https://pypi.org/project/microsoft-agents-authentication-msal/)
28
+
29
+ Provides secure authentication for your agents using Microsoft Authentication Library (MSAL). It handles getting tokens from Azure AD so your agent can securely communicate with Microsoft services like Teams, Graph API, and other Azure resources.
30
+
31
+ # What is this?
32
+
33
+ This library is part of the **Microsoft 365 Agents SDK for Python** - a comprehensive framework for building enterprise-grade conversational AI agents. The SDK enables developers to create intelligent agents that work across multiple platforms including Microsoft Teams, M365 Copilot, Copilot Studio, and web chat, with support for third-party integrations like Slack, Facebook Messenger, and Twilio.
34
+
35
+ ## Release Notes
36
+ <table style="width:100%">
37
+ <tr>
38
+ <th style="width:20%">Version</th>
39
+ <th style="width:20%">Date</th>
40
+ <th style="width:60%">Release Notes</th>
41
+ </tr>
42
+ <tr>
43
+ <td>0.5.0</td>
44
+ <td>2025-10-22</td>
45
+ <td>
46
+ <a href="https://github.com/microsoft/Agents-for-python/blob/main/changelog.md">
47
+ 0.5.0 Release Notes
48
+ </a>
49
+ </td>
50
+ </tr>
51
+ </table>
52
+
53
+ ## Packages Overview
54
+
55
+ We offer the following PyPI packages to create conversational experiences based on Agents:
56
+
57
+ | Package Name | PyPI Version | Description |
58
+ |--------------|-------------|-------------|
59
+ | `microsoft-agents-activity` | [![PyPI](https://img.shields.io/pypi/v/microsoft-agents-activity)](https://pypi.org/project/microsoft-agents-activity/) | Types and validators implementing the Activity protocol spec. |
60
+ | `microsoft-agents-hosting-core` | [![PyPI](https://img.shields.io/pypi/v/microsoft-agents-hosting-core)](https://pypi.org/project/microsoft-agents-hosting-core/) | Core library for Microsoft Agents hosting. |
61
+ | `microsoft-agents-hosting-aiohttp` | [![PyPI](https://img.shields.io/pypi/v/microsoft-agents-hosting-aiohttp)](https://pypi.org/project/microsoft-agents-hosting-aiohttp/) | Configures aiohttp to run the Agent. |
62
+ | `microsoft-agents-hosting-teams` | [![PyPI](https://img.shields.io/pypi/v/microsoft-agents-hosting-teams)](https://pypi.org/project/microsoft-agents-hosting-teams/) | Provides classes to host an Agent for Teams. |
63
+ | `microsoft-agents-storage-blob` | [![PyPI](https://img.shields.io/pypi/v/microsoft-agents-storage-blob)](https://pypi.org/project/microsoft-agents-storage-blob/) | Extension to use Azure Blob as storage. |
64
+ | `microsoft-agents-storage-cosmos` | [![PyPI](https://img.shields.io/pypi/v/microsoft-agents-storage-cosmos)](https://pypi.org/project/microsoft-agents-storage-cosmos/) | Extension to use CosmosDB as storage. |
65
+ | `microsoft-agents-authentication-msal` | [![PyPI](https://img.shields.io/pypi/v/microsoft-agents-authentication-msal)](https://pypi.org/project/microsoft-agents-authentication-msal/) | MSAL-based authentication for Microsoft Agents. |
66
+
67
+ Additionally we provide a Copilot Studio Client, to interact with Agents created in CopilotStudio:
68
+
69
+ | Package Name | PyPI Version | Description |
70
+ |--------------|-------------|-------------|
71
+ | `microsoft-agents-copilotstudio-client` | [![PyPI](https://img.shields.io/pypi/v/microsoft-agents-copilotstudio-client)](https://pypi.org/project/microsoft-agents-copilotstudio-client/) | Direct to Engine client to interact with Agents created in CopilotStudio |
72
+
73
+ ## Installation
74
+
75
+ ```bash
76
+ pip install microsoft-agents-authentication-msal
77
+ ```
78
+
79
+ ## Quick Start
80
+
81
+ ### Basic Setup with Client Secret
82
+
83
+ Define your client secrets in the ENV file
84
+ ```python
85
+ CONNECTIONS__SERVICE_CONNECTION__SETTINGS__CLIENTID=client-id
86
+ CONNECTIONS__SERVICE_CONNECTION__SETTINGS__CLIENTSECRET=client-secret
87
+ CONNECTIONS__SERVICE_CONNECTION__SETTINGS__TENANTID=tenant-id
88
+ ```
89
+
90
+ Load the Configuration (Code from [main.py Quickstart Sample](https://github.com/microsoft/Agents/blob/main/samples/python/quickstart/src/main.py))
91
+
92
+ ```python
93
+ from .start_server import start_server
94
+
95
+ start_server(
96
+ agent_application=AGENT_APP,
97
+ auth_configuration=CONNECTION_MANAGER.get_default_connection_configuration(),
98
+ )
99
+ ```
100
+ Then start the Agent (code snipped from (start_server.py Quickstart Sample](https://github.com/microsoft/Agents/blob/main/samples/python/quickstart/src/start_server.py)):
101
+
102
+ ```python
103
+ def start_server(
104
+ agent_application: AgentApplication, auth_configuration: AgentAuthConfiguration
105
+ ):
106
+ async def entry_point(req: Request) -> Response:
107
+ agent: AgentApplication = req.app["agent_app"]
108
+ adapter: CloudAdapter = req.app["adapter"]
109
+ return await start_agent_process(
110
+ req,
111
+ agent,
112
+ adapter,
113
+ )
114
+ [...]
115
+ ```
116
+
117
+ ## Authentication Types
118
+ The M365 Agents SDK in Python supports the following Auth types:
119
+ ```python
120
+ class AuthTypes(str, Enum):
121
+ certificate = "certificate"
122
+ certificate_subject_name = "CertificateSubjectName"
123
+ client_secret = "ClientSecret"
124
+ user_managed_identity = "UserManagedIdentity"
125
+ system_managed_identity = "SystemManagedIdentity"
126
+ ```
127
+
128
+ ## Key Classes
129
+
130
+ - **`MsalAuth`** - Core authentication provider using MSAL
131
+ - **`MsalConnectionManager`** - Manages multiple authentication connections
132
+
133
+ ## Features
134
+
135
+ ✅ **Multiple auth types** - Client secret, certificate, managed identity
136
+ ✅ **Token caching** - Automatic token refresh and caching
137
+ ✅ **Multi-tenant** - Support for different Azure AD tenants
138
+ ✅ **Agent-to-agent** - Secure communication between agents
139
+ ✅ **On-behalf-of** - Act on behalf of users
140
+
141
+ # Security Best Practices
142
+
143
+ - Store secrets in Azure Key Vault or environment variables
144
+ - Use managed identities when possible (no secrets to manage)
145
+ - Regularly rotate client secrets and certificates
146
+ - Use least-privilege principle for scopes and permissions
147
+
148
+ # Quick Links
149
+
150
+ - 📦 [All SDK Packages on PyPI](https://pypi.org/search/?q=microsoft-agents)
151
+ - 📖 [Complete Documentation](https://aka.ms/agents)
152
+ - 💡 [Python Samples Repository](https://github.com/microsoft/Agents/tree/main/samples/python)
153
+ - 🐛 [Report Issues](https://github.com/microsoft/Agents-for-python/issues)
154
+
155
+ # Sample Applications
156
+ Explore working examples in the [Python samples repository](https://github.com/microsoft/Agents/tree/main/samples/python):
157
+
158
+ |Name|Description|README|
159
+ |----|----|----|
160
+ |Quickstart|Simplest agent|[Quickstart](https://github.com/microsoft/Agents/blob/main/samples/python/quickstart/README.md)|
161
+ |Auto Sign In|Simple OAuth agent using Graph and GitHub|[auto-signin](https://github.com/microsoft/Agents/blob/main/samples/python/auto-signin/README.md)|
162
+ |OBO Authorization|OBO flow to access a Copilot Studio Agent|[obo-authorization](https://github.com/microsoft/Agents/blob/main/samples/python/obo-authorization/README.md)|
163
+ |Semantic Kernel Integration|A weather agent built with Semantic Kernel|[semantic-kernel-multiturn](https://github.com/microsoft/Agents/blob/main/samples/python/semantic-kernel-multiturn/README.md)|
164
+ |Streaming Agent|Streams OpenAI responses|[azure-ai-streaming](https://github.com/microsoft/Agents/blob/main/samples/python/azureai-streaming/README.md)|
165
+ |Copilot Studio Client|Console app to consume a Copilot Studio Agent|[copilotstudio-client](https://github.com/microsoft/Agents/blob/main/samples/python/copilotstudio-client/README.md)|
166
+ |Cards Agent|Agent that uses rich cards to enhance conversation design |[cards](https://github.com/microsoft/Agents/blob/main/samples/python/cards/README.md)|
@@ -0,0 +1,10 @@
1
+ microsoft_agents/authentication/msal/__init__.py,sha256=hjPpakL4zyqeCTEBOUCcHaRnSpG80q-L0csG5HMalYI,151
2
+ microsoft_agents/authentication/msal/msal_auth.py,sha256=iWXAFYYv0MoxK_mvuRq_cren8fJZWrBbW7hsSGmTDLQ,17057
3
+ microsoft_agents/authentication/msal/msal_connection_manager.py,sha256=v7o0ONzjId1G6Ta7IjHc1NtSeM3NWH4t7YilrwJzvYg,5713
4
+ microsoft_agents/authentication/msal/errors/__init__.py,sha256=9dbI_fGa0J4-qq6mTwdAIjaDADDFypenn4ZcsK-F4nE,449
5
+ microsoft_agents/authentication/msal/errors/error_resources.py,sha256=BIZNjhKLNZmyggblBkyQ3R2pGq3VkllEoni6QgBI4hw,1849
6
+ microsoft_agents_authentication_msal-0.6.1.dist-info/licenses/LICENSE,sha256=ws_MuBL-SCEBqPBFl9_FqZkaaydIJmxHrJG2parhU4M,1141
7
+ microsoft_agents_authentication_msal-0.6.1.dist-info/METADATA,sha256=BEbmKel2DbB7kq74vcPcrfFqEpYiwnZz2tOnunwm8PQ,8363
8
+ microsoft_agents_authentication_msal-0.6.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ microsoft_agents_authentication_msal-0.6.1.dist-info/top_level.txt,sha256=lWKcT4v6fTA_NgsuHdNvuMjSrkiBMXohn64ApY7Xi8A,17
10
+ microsoft_agents_authentication_msal-0.6.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Microsoft Corporation.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE
@@ -0,0 +1 @@
1
+ microsoft_agents