microsoft-agents-authentication-msal 0.4.0.dev10__tar.gz → 0.4.0.dev16__tar.gz

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.
Files changed (14) hide show
  1. {microsoft_agents_authentication_msal-0.4.0.dev10 → microsoft_agents_authentication_msal-0.4.0.dev16}/PKG-INFO +2 -2
  2. microsoft_agents_authentication_msal-0.4.0.dev16/microsoft_agents/authentication/msal/msal_auth.py +392 -0
  3. microsoft_agents_authentication_msal-0.4.0.dev16/microsoft_agents/authentication/msal/msal_connection_manager.py +131 -0
  4. {microsoft_agents_authentication_msal-0.4.0.dev10 → microsoft_agents_authentication_msal-0.4.0.dev16}/microsoft_agents_authentication_msal.egg-info/PKG-INFO +2 -2
  5. {microsoft_agents_authentication_msal-0.4.0.dev10 → microsoft_agents_authentication_msal-0.4.0.dev16}/microsoft_agents_authentication_msal.egg-info/requires.txt +1 -1
  6. microsoft_agents_authentication_msal-0.4.0.dev10/microsoft_agents/authentication/msal/msal_auth.py +0 -188
  7. microsoft_agents_authentication_msal-0.4.0.dev10/microsoft_agents/authentication/msal/msal_connection_manager.py +0 -72
  8. {microsoft_agents_authentication_msal-0.4.0.dev10 → microsoft_agents_authentication_msal-0.4.0.dev16}/microsoft_agents/authentication/msal/__init__.py +0 -0
  9. {microsoft_agents_authentication_msal-0.4.0.dev10 → microsoft_agents_authentication_msal-0.4.0.dev16}/microsoft_agents_authentication_msal.egg-info/SOURCES.txt +0 -0
  10. {microsoft_agents_authentication_msal-0.4.0.dev10 → microsoft_agents_authentication_msal-0.4.0.dev16}/microsoft_agents_authentication_msal.egg-info/dependency_links.txt +0 -0
  11. {microsoft_agents_authentication_msal-0.4.0.dev10 → microsoft_agents_authentication_msal-0.4.0.dev16}/microsoft_agents_authentication_msal.egg-info/top_level.txt +0 -0
  12. {microsoft_agents_authentication_msal-0.4.0.dev10 → microsoft_agents_authentication_msal-0.4.0.dev16}/pyproject.toml +0 -0
  13. {microsoft_agents_authentication_msal-0.4.0.dev10 → microsoft_agents_authentication_msal-0.4.0.dev16}/setup.cfg +0 -0
  14. {microsoft_agents_authentication_msal-0.4.0.dev10 → microsoft_agents_authentication_msal-0.4.0.dev16}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: microsoft-agents-authentication-msal
3
- Version: 0.4.0.dev10
3
+ Version: 0.4.0.dev16
4
4
  Summary: A msal-based authentication library for Microsoft Agents
5
5
  Author: Microsoft Corporation
6
6
  Project-URL: Homepage, https://github.com/microsoft/Agents
@@ -8,7 +8,7 @@ Classifier: Programming Language :: Python :: 3
8
8
  Classifier: License :: OSI Approved :: MIT License
9
9
  Classifier: Operating System :: OS Independent
10
10
  Requires-Python: >=3.9
11
- Requires-Dist: microsoft-agents-hosting-core==0.4.0.dev10
11
+ Requires-Dist: microsoft-agents-hosting-core==0.4.0.dev16
12
12
  Requires-Dist: msal>=1.31.1
13
13
  Requires-Dist: requests>=2.32.3
14
14
  Requires-Dist: cryptography>=44.0.0
@@ -0,0 +1,392 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import jwt
5
+ from typing import Optional
6
+ from urllib.parse import urlparse, ParseResult as URI
7
+ from msal import (
8
+ ConfidentialClientApplication,
9
+ ManagedIdentityClient,
10
+ UserAssignedManagedIdentity,
11
+ SystemAssignedManagedIdentity,
12
+ )
13
+ from requests import Session
14
+ from cryptography.x509 import load_pem_x509_certificate
15
+ from cryptography.hazmat.backends import default_backend
16
+ from cryptography.hazmat.primitives import hashes
17
+
18
+ from microsoft_agents.hosting.core import (
19
+ AuthTypes,
20
+ AccessTokenProviderBase,
21
+ AgentAuthConfiguration,
22
+ )
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ # this is deferred because jwt.decode is expensive and we don't want to do it unless we
28
+ # have logging.DEBUG enabled
29
+ class _DeferredLogOfBlueprintId:
30
+ def __init__(self, jwt_token: str):
31
+ self.jwt_token = jwt_token
32
+
33
+ def __str__(self):
34
+ payload = jwt.decode(self.jwt_token, options={"verify_signature": False})
35
+ agentic_blueprint_id = payload.get("xms_par_app_azp")
36
+ return f"Agentic blueprint id: {agentic_blueprint_id}"
37
+
38
+
39
+ class MsalAuth(AccessTokenProviderBase):
40
+
41
+ _client_credential_cache = None
42
+
43
+ def __init__(self, msal_configuration: AgentAuthConfiguration):
44
+ self._msal_configuration = msal_configuration
45
+ logger.debug(
46
+ f"Initializing MsalAuth with configuration: {self._msal_configuration}"
47
+ )
48
+
49
+ async def get_access_token(
50
+ self, resource_url: str, scopes: list[str], force_refresh: bool = False
51
+ ) -> str:
52
+ logger.debug(
53
+ f"Requesting access token for resource: {resource_url}, scopes: {scopes}"
54
+ )
55
+ valid_uri, instance_uri = self._uri_validator(resource_url)
56
+ if not valid_uri:
57
+ raise ValueError("Invalid instance URL")
58
+
59
+ local_scopes = self._resolve_scopes_list(instance_uri, scopes)
60
+ msal_auth_client = self._create_client_application()
61
+
62
+ if isinstance(msal_auth_client, ManagedIdentityClient):
63
+ logger.info("Acquiring token using Managed Identity Client.")
64
+ auth_result_payload = msal_auth_client.acquire_token_for_client(
65
+ resource=resource_url
66
+ )
67
+ elif isinstance(msal_auth_client, ConfidentialClientApplication):
68
+ logger.info("Acquiring token using Confidential Client Application.")
69
+ auth_result_payload = msal_auth_client.acquire_token_for_client(
70
+ scopes=local_scopes
71
+ )
72
+ else:
73
+ auth_result_payload = None
74
+
75
+ res = auth_result_payload.get("access_token") if auth_result_payload else None
76
+ if not res:
77
+ logger.error("Failed to acquire token for resource %s", auth_result_payload)
78
+ raise ValueError(f"Failed to acquire token. {str(auth_result_payload)}")
79
+ return res
80
+
81
+ async def acquire_token_on_behalf_of(
82
+ self, scopes: list[str], user_assertion: str
83
+ ) -> str:
84
+ """
85
+ Acquire a token on behalf of a user.
86
+ :param scopes: The scopes for which to get the token.
87
+ :param user_assertion: The user assertion token.
88
+ :return: The access token as a string.
89
+ """
90
+
91
+ msal_auth_client = self._create_client_application()
92
+ if isinstance(msal_auth_client, ManagedIdentityClient):
93
+ logger.error(
94
+ "Attempted on-behalf-of flow with Managed Identity authentication."
95
+ )
96
+ raise NotImplementedError(
97
+ "On-behalf-of flow is not supported with Managed Identity authentication."
98
+ )
99
+ elif isinstance(msal_auth_client, ConfidentialClientApplication):
100
+ # TODO: Handling token error / acquisition failed
101
+
102
+ token = msal_auth_client.acquire_token_on_behalf_of(
103
+ user_assertion=user_assertion, scopes=scopes
104
+ )
105
+
106
+ if "access_token" not in token:
107
+ logger.error(
108
+ f"Failed to acquire token on behalf of user: {user_assertion}"
109
+ )
110
+ raise ValueError(f"Failed to acquire token. {str(token)}")
111
+
112
+ return token["access_token"]
113
+
114
+ logger.error(
115
+ f"On-behalf-of flow is not supported with the current authentication type: {msal_auth_client.__class__.__name__}"
116
+ )
117
+ raise NotImplementedError(
118
+ f"On-behalf-of flow is not supported with the current authentication type: {msal_auth_client.__class__.__name__}"
119
+ )
120
+
121
+ def _create_client_application(
122
+ self,
123
+ ) -> ManagedIdentityClient | ConfidentialClientApplication:
124
+ msal_auth_client = None
125
+
126
+ if self._msal_configuration.AUTH_TYPE == AuthTypes.user_managed_identity:
127
+ msal_auth_client = ManagedIdentityClient(
128
+ UserAssignedManagedIdentity(
129
+ client_id=self._msal_configuration.CLIENT_ID
130
+ ),
131
+ http_client=Session(),
132
+ )
133
+
134
+ elif self._msal_configuration.AUTH_TYPE == AuthTypes.system_managed_identity:
135
+ msal_auth_client = ManagedIdentityClient(
136
+ SystemAssignedManagedIdentity(),
137
+ http_client=Session(),
138
+ )
139
+ else:
140
+ authority_path = self._msal_configuration.TENANT_ID or "botframework.com"
141
+ authority = f"https://login.microsoftonline.com/{authority_path}"
142
+
143
+ if self._client_credential_cache:
144
+ logger.info("Using cached client credentials for MSAL authentication.")
145
+ pass
146
+ elif self._msal_configuration.AUTH_TYPE == AuthTypes.client_secret:
147
+ self._client_credential_cache = self._msal_configuration.CLIENT_SECRET
148
+ elif self._msal_configuration.AUTH_TYPE == AuthTypes.certificate:
149
+ with open(self._msal_configuration.CERT_KEY_FILE) as file:
150
+ logger.info(
151
+ "Loading certificate private key for MSAL authentication."
152
+ )
153
+ private_key = file.read()
154
+
155
+ with open(self._msal_configuration.CERT_PEM_FILE) as file:
156
+ logger.info("Loading public certificate for MSAL authentication.")
157
+ public_certificate = file.read()
158
+
159
+ # Create an X509 object and calculate the thumbprint
160
+ logger.info("Calculating thumbprint for the public certificate.")
161
+ cert = load_pem_x509_certificate(
162
+ data=bytes(public_certificate, "UTF-8"), backend=default_backend()
163
+ )
164
+ thumbprint = cert.fingerprint(hashes.SHA1()).hex()
165
+
166
+ self._client_credential_cache = {
167
+ "thumbprint": thumbprint,
168
+ "private_key": private_key,
169
+ }
170
+ else:
171
+ logger.error(
172
+ f"Unsupported authentication type: {self._msal_configuration.AUTH_TYPE}"
173
+ )
174
+ raise NotImplementedError("Authentication type not supported")
175
+
176
+ msal_auth_client = ConfidentialClientApplication(
177
+ client_id=self._msal_configuration.CLIENT_ID,
178
+ authority=authority,
179
+ client_credential=self._client_credential_cache,
180
+ )
181
+
182
+ return msal_auth_client
183
+
184
+ @staticmethod
185
+ def _uri_validator(url_str: str) -> tuple[bool, Optional[URI]]:
186
+ try:
187
+ result = urlparse(url_str)
188
+ return all([result.scheme, result.netloc]), result
189
+ except AttributeError:
190
+ logger.error(f"URI parsing error for {url_str}")
191
+ return False, None
192
+
193
+ def _resolve_scopes_list(self, instance_url: URI, scopes=None) -> list[str]:
194
+ if scopes:
195
+ return scopes
196
+
197
+ temp_list: list[str] = []
198
+ for scope in self._msal_configuration.SCOPES:
199
+ scope_placeholder = scope
200
+ if "{instance}" in scope_placeholder.lower():
201
+ scope_placeholder = scope_placeholder.replace(
202
+ "{instance}", f"{instance_url.scheme}://{instance_url.hostname}"
203
+ )
204
+ temp_list.append(scope_placeholder)
205
+ logger.debug(f"Resolved scopes: {temp_list}")
206
+ return temp_list
207
+
208
+ # the call to MSAL is blocking, but in the future we want to create an asyncio task
209
+ # to avoid this
210
+ async def get_agentic_application_token(
211
+ self, agent_app_instance_id: str
212
+ ) -> Optional[str]:
213
+ """Gets the agentic application token for the given agent application instance ID.
214
+
215
+ :param agent_app_instance_id: The agent application instance ID.
216
+ :type agent_app_instance_id: str
217
+ :return: The agentic application token, or None if not found.
218
+ :rtype: Optional[str]
219
+ """
220
+
221
+ if not agent_app_instance_id:
222
+ raise ValueError("Agent application instance Id must be provided.")
223
+
224
+ logger.info(
225
+ "Attempting to get agentic application token from agent_app_instance_id %s",
226
+ agent_app_instance_id,
227
+ )
228
+ msal_auth_client = self._create_client_application()
229
+
230
+ if isinstance(msal_auth_client, ConfidentialClientApplication):
231
+
232
+ # https://github.dev/AzureAD/microsoft-authentication-library-for-dotnet
233
+ auth_result_payload = msal_auth_client.acquire_token_for_client(
234
+ ["api://AzureAdTokenExchange/.default"],
235
+ data={"fmi_path": agent_app_instance_id},
236
+ )
237
+
238
+ if auth_result_payload:
239
+ return auth_result_payload.get("access_token")
240
+
241
+ return None
242
+
243
+ async def get_agentic_instance_token(
244
+ self, agent_app_instance_id: str
245
+ ) -> tuple[str, str]:
246
+ """Gets the agentic instance token for the given agent application instance ID.
247
+
248
+ :param agent_app_instance_id: The agent application instance ID.
249
+ :type agent_app_instance_id: str
250
+ :return: A tuple containing the agentic instance token and the agent application token.
251
+ :rtype: tuple[str, str]
252
+ """
253
+
254
+ if not agent_app_instance_id:
255
+ raise ValueError("Agent application instance Id must be provided.")
256
+
257
+ logger.info(
258
+ "Attempting to get agentic instance token from agent_app_instance_id %s",
259
+ agent_app_instance_id,
260
+ )
261
+ agent_token_result = await self.get_agentic_application_token(
262
+ agent_app_instance_id
263
+ )
264
+
265
+ if not agent_token_result:
266
+ logger.error(
267
+ "Failed to acquire agentic instance token or agent token for agent_app_instance_id %s",
268
+ agent_app_instance_id,
269
+ )
270
+ raise Exception(
271
+ f"Failed to acquire agentic instance token or agent token for agent_app_instance_id {agent_app_instance_id}"
272
+ )
273
+
274
+ authority = (
275
+ f"https://login.microsoftonline.com/{self._msal_configuration.TENANT_ID}"
276
+ )
277
+
278
+ instance_app = ConfidentialClientApplication(
279
+ client_id=agent_app_instance_id,
280
+ authority=authority,
281
+ client_credential={"client_assertion": agent_token_result},
282
+ )
283
+
284
+ agentic_instance_token = instance_app.acquire_token_for_client(
285
+ ["api://AzureAdTokenExchange/.default"]
286
+ )
287
+
288
+ if not agentic_instance_token:
289
+ logger.error(
290
+ "Failed to acquire agentic instance token or agent token for agent_app_instance_id %s",
291
+ agent_app_instance_id,
292
+ )
293
+ raise Exception(
294
+ f"Failed to acquire agentic instance token or agent token for agent_app_instance_id {agent_app_instance_id}"
295
+ )
296
+
297
+ # future scenario where we don't know the blueprint id upfront
298
+
299
+ token = agentic_instance_token.get("access_token")
300
+ if not token:
301
+ logger.error(
302
+ "Failed to acquire agentic instance token, %s", agentic_instance_token
303
+ )
304
+ raise ValueError(f"Failed to acquire token. {str(agentic_instance_token)}")
305
+
306
+ logger.debug(_DeferredLogOfBlueprintId(token))
307
+
308
+ return agentic_instance_token["access_token"], agent_token_result
309
+
310
+ async def get_agentic_user_token(
311
+ self, agent_app_instance_id: str, upn: str, scopes: list[str]
312
+ ) -> Optional[str]:
313
+ """Gets the agentic user token for the given agent application instance ID and user principal name and the scopes.
314
+
315
+ :param agent_app_instance_id: The agent application instance ID.
316
+ :type agent_app_instance_id: str
317
+ :param upn: The user principal name.
318
+ :type upn: str
319
+ :param scopes: The scopes to request for the token.
320
+ :type scopes: list[str]
321
+ :return: The agentic user token, or None if not found.
322
+ :rtype: Optional[str]
323
+ """
324
+ if not agent_app_instance_id or not upn:
325
+ raise ValueError(
326
+ "Agent application instance Id and user principal name must be provided."
327
+ )
328
+
329
+ logger.info(
330
+ "Attempting to get agentic user token from agent_app_instance_id %s and upn %s",
331
+ agent_app_instance_id,
332
+ upn,
333
+ )
334
+ instance_token, agent_token = await self.get_agentic_instance_token(
335
+ agent_app_instance_id
336
+ )
337
+
338
+ if not instance_token or not agent_token:
339
+ logger.error(
340
+ "Failed to acquire instance token or agent token for agent_app_instance_id %s and upn %s",
341
+ agent_app_instance_id,
342
+ upn,
343
+ )
344
+ raise Exception(
345
+ f"Failed to acquire instance token or agent token for agent_app_instance_id {agent_app_instance_id} and upn {upn}"
346
+ )
347
+
348
+ authority = (
349
+ f"https://login.microsoftonline.com/{self._msal_configuration.TENANT_ID}"
350
+ )
351
+
352
+ instance_app = ConfidentialClientApplication(
353
+ client_id=agent_app_instance_id,
354
+ authority=authority,
355
+ client_credential={"client_assertion": agent_token},
356
+ )
357
+
358
+ logger.info(
359
+ "Acquiring agentic user token for agent_app_instance_id %s and upn %s",
360
+ agent_app_instance_id,
361
+ upn,
362
+ )
363
+ auth_result_payload = instance_app.acquire_token_for_client(
364
+ scopes,
365
+ data={
366
+ "username": upn,
367
+ "user_federated_identity_credential": instance_token,
368
+ "grant_type": "user_fic",
369
+ },
370
+ )
371
+
372
+ if not auth_result_payload:
373
+ logger.error(
374
+ "Failed to acquire agentic user token for agent_app_instance_id %s and upn %s, %s",
375
+ agent_app_instance_id,
376
+ upn,
377
+ auth_result_payload,
378
+ )
379
+ return None
380
+
381
+ access_token = auth_result_payload.get("access_token")
382
+ if not access_token:
383
+ logger.error(
384
+ "Failed to acquire agentic user token for agent_app_instance_id %s and upn %s, %s",
385
+ agent_app_instance_id,
386
+ upn,
387
+ auth_result_payload,
388
+ )
389
+ return None
390
+
391
+ logger.info("Acquired agentic user token response.")
392
+ return access_token
@@ -0,0 +1,131 @@
1
+ import re
2
+ from typing import Dict, List, Optional
3
+ from microsoft_agents.hosting.core import (
4
+ AgentAuthConfiguration,
5
+ AccessTokenProviderBase,
6
+ ClaimsIdentity,
7
+ Connections,
8
+ )
9
+
10
+ from .msal_auth import MsalAuth
11
+
12
+
13
+ class MsalConnectionManager(Connections):
14
+ _connections: Dict[str, MsalAuth]
15
+ _connections_map: List[Dict[str, str]]
16
+ _service_connection_configuration: AgentAuthConfiguration
17
+
18
+ def __init__(
19
+ self,
20
+ connections_configurations: Optional[Dict[str, AgentAuthConfiguration]] = None,
21
+ connections_map: Optional[List[Dict[str, str]]] = None,
22
+ **kwargs,
23
+ ):
24
+ """
25
+ Initialize the MSAL connection manager.
26
+
27
+ :arg connections_configurations: A dictionary of connection configurations.
28
+ :type connections_configurations: Dict[str, AgentAuthConfiguration]
29
+ :arg connections_map: A list of connection mappings.
30
+ :type connections_map: List[Dict[str, str]]
31
+ :raises ValueError: If no service connection configuration is provided.
32
+ """
33
+
34
+ self._connections: Dict[str, MsalAuth] = {}
35
+ self._connections_map = connections_map or kwargs.get("CONNECTIONSMAP", {})
36
+ self._service_connection_configuration: AgentAuthConfiguration = None
37
+
38
+ if connections_configurations:
39
+ for (
40
+ connection_name,
41
+ connection_settings,
42
+ ) in connections_configurations.items():
43
+ self._connections[connection_name] = MsalAuth(
44
+ AgentAuthConfiguration(**connection_settings)
45
+ )
46
+ else:
47
+ raw_configurations: Dict[str, Dict] = kwargs.get("CONNECTIONS", {})
48
+ for connection_name, connection_settings in raw_configurations.items():
49
+ parsed_configuration = AgentAuthConfiguration(
50
+ **connection_settings.get("SETTINGS", {})
51
+ )
52
+ self._connections[connection_name] = MsalAuth(parsed_configuration)
53
+ if connection_name == "SERVICE_CONNECTION":
54
+ self._service_connection_configuration = parsed_configuration
55
+
56
+ if not self._connections.get("SERVICE_CONNECTION", None):
57
+ raise ValueError("No service connection configuration provided.")
58
+
59
+ def get_connection(self, connection_name: Optional[str]) -> AccessTokenProviderBase:
60
+ """
61
+ Get the OAuth connection for the agent.
62
+
63
+ :arg connection_name: The name of the connection.
64
+ :type connection_name: str
65
+ :return: The OAuth connection for the agent.
66
+ :rtype: AccessTokenProviderBase
67
+ """
68
+ # should never be None
69
+ return self._connections.get(connection_name, None)
70
+
71
+ def get_default_connection(self) -> AccessTokenProviderBase:
72
+ """
73
+ Get the default OAuth connection for the agent.
74
+ """
75
+ # should never be None
76
+ return self._connections.get("SERVICE_CONNECTION", None)
77
+
78
+ def get_token_provider(
79
+ self, claims_identity: ClaimsIdentity, service_url: str
80
+ ) -> AccessTokenProviderBase:
81
+ """
82
+ Get the OAuth token provider for the agent.
83
+
84
+ :arg claims_identity: The claims identity of the bot.
85
+ :type claims_identity: ClaimsIdentity
86
+ :arg service_url: The service URL of the bot.
87
+ :type service_url: str
88
+ :return: The OAuth token provider for the agent.
89
+ :rtype: AccessTokenProviderBase
90
+ :raises ValueError: If no connection is found for the given audience and service URL.
91
+ """
92
+ if not claims_identity or not service_url:
93
+ raise ValueError(
94
+ "Claims identity and Service URL are required to get the token provider."
95
+ )
96
+
97
+ if not self._connections_map:
98
+ return self.get_default_connection()
99
+
100
+ aud = claims_identity.get_app_id() or ""
101
+ for item in self._connections_map:
102
+ audience_match = True
103
+ item_aud = item.get("AUDIENCE", "")
104
+ if item_aud:
105
+ audience_match = item_aud.lower() == aud.lower()
106
+
107
+ if audience_match:
108
+ item_service_url = item.get("SERVICEURL", "")
109
+ if item_service_url == "*" or item_service_url == "":
110
+ connection_name = item.get("CONNECTION")
111
+ connection = self.get_connection(connection_name)
112
+ if connection:
113
+ return connection
114
+
115
+ else:
116
+ res = re.match(item_service_url, service_url, re.IGNORECASE)
117
+ if res:
118
+ connection_name = item.get("CONNECTION")
119
+ connection = self.get_connection(connection_name)
120
+ if connection:
121
+ return connection
122
+
123
+ raise ValueError(
124
+ f"No connection found for audience '{aud}' and serviceUrl '{service_url}'."
125
+ )
126
+
127
+ def get_default_connection_configuration(self) -> AgentAuthConfiguration:
128
+ """
129
+ Get the default connection configuration for the agent.
130
+ """
131
+ return self._service_connection_configuration
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: microsoft-agents-authentication-msal
3
- Version: 0.4.0.dev10
3
+ Version: 0.4.0.dev16
4
4
  Summary: A msal-based authentication library for Microsoft Agents
5
5
  Author: Microsoft Corporation
6
6
  Project-URL: Homepage, https://github.com/microsoft/Agents
@@ -8,7 +8,7 @@ Classifier: Programming Language :: Python :: 3
8
8
  Classifier: License :: OSI Approved :: MIT License
9
9
  Classifier: Operating System :: OS Independent
10
10
  Requires-Python: >=3.9
11
- Requires-Dist: microsoft-agents-hosting-core==0.4.0.dev10
11
+ Requires-Dist: microsoft-agents-hosting-core==0.4.0.dev16
12
12
  Requires-Dist: msal>=1.31.1
13
13
  Requires-Dist: requests>=2.32.3
14
14
  Requires-Dist: cryptography>=44.0.0
@@ -1,4 +1,4 @@
1
- microsoft-agents-hosting-core==0.4.0.dev10
1
+ microsoft-agents-hosting-core==0.4.0.dev16
2
2
  msal>=1.31.1
3
3
  requests>=2.32.3
4
4
  cryptography>=44.0.0
@@ -1,188 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import logging
4
- from typing import Optional
5
- from urllib.parse import urlparse, ParseResult as URI
6
- from msal import (
7
- ConfidentialClientApplication,
8
- ManagedIdentityClient,
9
- UserAssignedManagedIdentity,
10
- SystemAssignedManagedIdentity,
11
- )
12
- from requests import Session
13
- from cryptography.x509 import load_pem_x509_certificate
14
- from cryptography.hazmat.backends import default_backend
15
- from cryptography.hazmat.primitives import hashes
16
-
17
- from microsoft_agents.hosting.core import (
18
- AuthTypes,
19
- AccessTokenProviderBase,
20
- AgentAuthConfiguration,
21
- )
22
-
23
- logger = logging.getLogger(__name__)
24
-
25
-
26
- class MsalAuth(AccessTokenProviderBase):
27
-
28
- _client_credential_cache = None
29
-
30
- def __init__(self, msal_configuration: AgentAuthConfiguration):
31
- self._msal_configuration = msal_configuration
32
- logger.debug(
33
- f"Initializing MsalAuth with configuration: {self._msal_configuration}"
34
- )
35
-
36
- async def get_access_token(
37
- self, resource_url: str, scopes: list[str], force_refresh: bool = False
38
- ) -> str:
39
- logger.debug(
40
- f"Requesting access token for resource: {resource_url}, scopes: {scopes}"
41
- )
42
- valid_uri, instance_uri = self._uri_validator(resource_url)
43
- if not valid_uri:
44
- raise ValueError("Invalid instance URL")
45
-
46
- local_scopes = self._resolve_scopes_list(instance_uri, scopes)
47
- msal_auth_client = self._create_client_application()
48
-
49
- if isinstance(msal_auth_client, ManagedIdentityClient):
50
- logger.info("Acquiring token using Managed Identity Client.")
51
- auth_result_payload = msal_auth_client.acquire_token_for_client(
52
- resource=resource_url
53
- )
54
- elif isinstance(msal_auth_client, ConfidentialClientApplication):
55
- logger.info("Acquiring token using Confidential Client Application.")
56
- auth_result_payload = msal_auth_client.acquire_token_for_client(
57
- scopes=local_scopes
58
- )
59
-
60
- # TODO: Handling token error / acquisition failed
61
- return auth_result_payload["access_token"]
62
-
63
- async def aquire_token_on_behalf_of(
64
- self, scopes: list[str], user_assertion: str
65
- ) -> str:
66
- """
67
- Acquire a token on behalf of a user.
68
- :param scopes: The scopes for which to get the token.
69
- :param user_assertion: The user assertion token.
70
- :return: The access token as a string.
71
- """
72
-
73
- msal_auth_client = self._create_client_application()
74
- if isinstance(msal_auth_client, ManagedIdentityClient):
75
- logger.error(
76
- "Attempted on-behalf-of flow with Managed Identity authentication."
77
- )
78
- raise NotImplementedError(
79
- "On-behalf-of flow is not supported with Managed Identity authentication."
80
- )
81
- elif isinstance(msal_auth_client, ConfidentialClientApplication):
82
- # TODO: Handling token error / acquisition failed
83
-
84
- token = msal_auth_client.acquire_token_on_behalf_of(
85
- user_assertion=user_assertion, scopes=scopes
86
- )
87
-
88
- if "access_token" not in token:
89
- logger.error(
90
- f"Failed to acquire token on behalf of user: {user_assertion}"
91
- )
92
- raise ValueError(f"Failed to acquire token. {str(token)}")
93
-
94
- return token["access_token"]
95
-
96
- logger.error(
97
- f"On-behalf-of flow is not supported with the current authentication type: {msal_auth_client.__class__.__name__}"
98
- )
99
- raise NotImplementedError(
100
- f"On-behalf-of flow is not supported with the current authentication type: {msal_auth_client.__class__.__name__}"
101
- )
102
-
103
- def _create_client_application(
104
- self,
105
- ) -> ManagedIdentityClient | ConfidentialClientApplication:
106
- msal_auth_client = None
107
-
108
- if self._msal_configuration.AUTH_TYPE == AuthTypes.user_managed_identity:
109
- msal_auth_client = ManagedIdentityClient(
110
- UserAssignedManagedIdentity(
111
- client_id=self._msal_configuration.CLIENT_ID
112
- ),
113
- http_client=Session(),
114
- )
115
-
116
- elif self._msal_configuration.AUTH_TYPE == AuthTypes.system_managed_identity:
117
- msal_auth_client = ManagedIdentityClient(
118
- SystemAssignedManagedIdentity(),
119
- http_client=Session(),
120
- )
121
- else:
122
- authority_path = self._msal_configuration.TENANT_ID or "botframework.com"
123
- authority = f"https://login.microsoftonline.com/{authority_path}"
124
-
125
- if self._client_credential_cache:
126
- logger.info("Using cached client credentials for MSAL authentication.")
127
- pass
128
- elif self._msal_configuration.AUTH_TYPE == AuthTypes.client_secret:
129
- self._client_credential_cache = self._msal_configuration.CLIENT_SECRET
130
- elif self._msal_configuration.AUTH_TYPE == AuthTypes.certificate:
131
- with open(self._msal_configuration.CERT_KEY_FILE) as file:
132
- logger.info(
133
- "Loading certificate private key for MSAL authentication."
134
- )
135
- private_key = file.read()
136
-
137
- with open(self._msal_configuration.CERT_PEM_FILE) as file:
138
- logger.info("Loading public certificate for MSAL authentication.")
139
- public_certificate = file.read()
140
-
141
- # Create an X509 object and calculate the thumbprint
142
- logger.info("Calculating thumbprint for the public certificate.")
143
- cert = load_pem_x509_certificate(
144
- data=bytes(public_certificate, "UTF-8"), backend=default_backend()
145
- )
146
- thumbprint = cert.fingerprint(hashes.SHA1()).hex()
147
-
148
- self._client_credential_cache = {
149
- "thumbprint": thumbprint,
150
- "private_key": private_key,
151
- }
152
- else:
153
- logger.error(
154
- f"Unsupported authentication type: {self._msal_configuration.AUTH_TYPE}"
155
- )
156
- raise NotImplementedError("Authentication type not supported")
157
-
158
- msal_auth_client = ConfidentialClientApplication(
159
- client_id=self._msal_configuration.CLIENT_ID,
160
- authority=authority,
161
- client_credential=self._client_credential_cache,
162
- )
163
-
164
- return msal_auth_client
165
-
166
- @staticmethod
167
- def _uri_validator(url_str: str) -> tuple[bool, Optional[URI]]:
168
- try:
169
- result = urlparse(url_str)
170
- return all([result.scheme, result.netloc]), result
171
- except AttributeError:
172
- logger.error(f"URI parsing error for {url_str}")
173
- return False, None
174
-
175
- def _resolve_scopes_list(self, instance_url: URI, scopes=None) -> list[str]:
176
- if scopes:
177
- return scopes
178
-
179
- temp_list: list[str] = []
180
- for scope in self._msal_configuration.SCOPES:
181
- scope_placeholder = scope
182
- if "{instance}" in scope_placeholder.lower():
183
- scope_placeholder = scope_placeholder.replace(
184
- "{instance}", f"{instance_url.scheme}://{instance_url.hostname}"
185
- )
186
- temp_list.append(scope_placeholder)
187
- logger.debug(f"Resolved scopes: {temp_list}")
188
- return temp_list
@@ -1,72 +0,0 @@
1
- from typing import Dict, List, Optional
2
- from microsoft_agents.hosting.core import (
3
- AgentAuthConfiguration,
4
- AccessTokenProviderBase,
5
- ClaimsIdentity,
6
- Connections,
7
- )
8
-
9
- from .msal_auth import MsalAuth
10
-
11
-
12
- class MsalConnectionManager(Connections):
13
-
14
- def __init__(
15
- self,
16
- connections_configurations: Dict[str, AgentAuthConfiguration] = None,
17
- connections_map: List[Dict[str, str]] = None,
18
- **kwargs
19
- ):
20
- self._connections: Dict[str, MsalAuth] = {}
21
- self._connections_map = connections_map or kwargs.get("CONNECTIONS_MAP", {})
22
- self._service_connection_configuration: AgentAuthConfiguration = None
23
-
24
- if connections_configurations:
25
- for (
26
- connection_name,
27
- connection_settings,
28
- ) in connections_configurations.items():
29
- self._connections[connection_name] = MsalAuth(
30
- AgentAuthConfiguration(**connection_settings)
31
- )
32
- else:
33
- raw_configurations: Dict[str, Dict] = kwargs.get("CONNECTIONS", {})
34
- for connection_name, connection_settings in raw_configurations.items():
35
- parsed_configuration = AgentAuthConfiguration(
36
- **connection_settings.get("SETTINGS", {})
37
- )
38
- self._connections[connection_name] = MsalAuth(parsed_configuration)
39
- if connection_name == "SERVICE_CONNECTION":
40
- self._service_connection_configuration = parsed_configuration
41
-
42
- if not self._connections.get("SERVICE_CONNECTION", None):
43
- raise ValueError("No service connection configuration provided.")
44
-
45
- def get_connection(self, connection_name: Optional[str]) -> AccessTokenProviderBase:
46
- """
47
- Get the OAuth connection for the agent.
48
- """
49
- return self._connections.get(connection_name, None)
50
-
51
- def get_default_connection(self) -> AccessTokenProviderBase:
52
- """
53
- Get the default OAuth connection for the agent.
54
- """
55
- return self._connections.get("SERVICE_CONNECTION", None)
56
-
57
- def get_token_provider(
58
- self, claims_identity: ClaimsIdentity, service_url: str
59
- ) -> AccessTokenProviderBase:
60
- """
61
- Get the OAuth token provider for the agent.
62
- """
63
- if not self._connections_map:
64
- return self.get_default_connection()
65
-
66
- # TODO: Implement logic to select the appropriate connection based on the connection map
67
-
68
- def get_default_connection_configuration(self) -> AgentAuthConfiguration:
69
- """
70
- Get the default connection configuration for the agent.
71
- """
72
- return self._service_connection_configuration