|
15 | 15 | JsonWebToken, |
16 | 16 | TokenProtocol, |
17 | 17 | ) |
18 | | -from microsoft.teams.api.auth.credentials import ManagedIdentityCredentials, TokenCredentials |
| 18 | +from microsoft.teams.api.auth.credentials import ( |
| 19 | + FederatedIdentityCredentials, |
| 20 | + ManagedIdentityCredentials, |
| 21 | + TokenCredentials, |
| 22 | +) |
19 | 23 | from microsoft.teams.common import ConsoleLogger |
20 | 24 | from msal import ( |
21 | 25 | ConfidentialClientApplication, |
22 | 26 | ManagedIdentityClient, |
| 27 | + SystemAssignedManagedIdentity, |
23 | 28 | UserAssignedManagedIdentity, |
24 | 29 | ) |
25 | 30 |
|
@@ -77,74 +82,166 @@ async def _get_token( |
77 | 82 | if caller_name: |
78 | 83 | self._logger.debug(f"No credentials provided for {caller_name}") |
79 | 84 | return None |
80 | | - if isinstance(credentials, (ClientCredentials, ManagedIdentityCredentials)): |
81 | | - msal_client = self._get_msal_client(tenant_id) |
82 | | - |
83 | | - # Handle different acquire_token_for_client signatures |
84 | | - if isinstance(msal_client, ManagedIdentityClient): |
85 | | - # ManagedIdentityClient expects resource as a keyword-only string parameter |
86 | | - scope = scope.removesuffix("/.default") |
87 | | - token_res: dict[str, Any] | None = await asyncio.to_thread( |
88 | | - lambda: msal_client.acquire_token_for_client(resource=scope) |
89 | | - ) |
90 | | - else: |
91 | | - # ConfidentialClientApplication expects scopes as a list |
92 | | - token_res: dict[str, Any] | None = await asyncio.to_thread( |
93 | | - lambda: msal_client.acquire_token_for_client([scope]) |
94 | | - ) |
95 | | - |
96 | | - if token_res.get("access_token", None): |
97 | | - access_token = token_res["access_token"] |
98 | | - return JsonWebToken(access_token) |
99 | | - else: |
100 | | - self._logger.debug(f"TokenRes: {token_res}") |
101 | | - error = token_res.get("error", "Error retrieving token") |
102 | | - if not isinstance(error, BaseException): |
103 | | - error = ValueError(error) |
104 | | - error_description = token_res.get("error_description", "Error retrieving token from MSAL") |
105 | | - self._logger.error(error_description) |
106 | | - raise error |
| 85 | + if isinstance(credentials, ClientCredentials): |
| 86 | + return await self._get_token_with_client_credentials(credentials, scope, tenant_id) |
| 87 | + elif isinstance(credentials, ManagedIdentityCredentials): |
| 88 | + return await self._get_token_with_managed_identity(credentials, scope) |
| 89 | + elif isinstance(credentials, FederatedIdentityCredentials): |
| 90 | + return await self._get_token_with_federated_identity(credentials, scope, tenant_id) |
107 | 91 | elif isinstance(credentials, TokenCredentials): |
108 | | - token = credentials.token(scope, tenant_id) |
109 | | - if isawaitable(token): |
110 | | - access_token = await token |
111 | | - else: |
112 | | - access_token = token |
| 92 | + return await self._get_token_with_token_provider(credentials, scope, tenant_id) |
| 93 | + |
| 94 | + return None |
| 95 | + |
| 96 | + async def _get_token_with_client_credentials( |
| 97 | + self, |
| 98 | + credentials: ClientCredentials, |
| 99 | + scope: str, |
| 100 | + tenant_id: str, |
| 101 | + ) -> TokenProtocol: |
| 102 | + """Get token using ClientCredentials (client secret).""" |
| 103 | + confidential_client = self._get_confidential_client(credentials, tenant_id) |
| 104 | + |
| 105 | + # ConfidentialClientApplication expects scopes as a list |
| 106 | + token_res: dict[str, Any] = await asyncio.to_thread( |
| 107 | + lambda: confidential_client.acquire_token_for_client([scope]) |
| 108 | + ) |
| 109 | + |
| 110 | + return self._handle_token_response(token_res) |
| 111 | + |
| 112 | + async def _get_token_with_managed_identity( |
| 113 | + self, |
| 114 | + credentials: ManagedIdentityCredentials, |
| 115 | + scope: str, |
| 116 | + ) -> TokenProtocol: |
| 117 | + """Get token using ManagedIdentityCredentials (direct, no federation).""" |
| 118 | + mi_client = self._get_managed_identity_client(credentials) |
| 119 | + |
| 120 | + # ManagedIdentityClient expects resource as a keyword-only string parameter |
| 121 | + resource = scope.removesuffix("/.default") |
| 122 | + token_res: dict[str, Any] = await asyncio.to_thread( |
| 123 | + lambda: mi_client.acquire_token_for_client(resource=resource) |
| 124 | + ) |
| 125 | + |
| 126 | + return self._handle_token_response(token_res) |
| 127 | + |
| 128 | + async def _get_token_with_federated_identity( |
| 129 | + self, |
| 130 | + credentials: FederatedIdentityCredentials, |
| 131 | + scope: str, |
| 132 | + tenant_id: str, |
| 133 | + ) -> TokenProtocol: |
| 134 | + """Get token using Federated Identity Credentials (two-step flow).""" |
| 135 | + |
| 136 | + # Step 1: Get MI token from api://AzureADTokenExchange |
| 137 | + mi_token = await self._acquire_managed_identity_token(credentials) |
| 138 | + |
| 139 | + # Step 2: Use MI token as client_assertion to get final access token |
| 140 | + confidential_client = ConfidentialClientApplication( |
| 141 | + credentials.client_id, |
| 142 | + client_credential={"client_assertion": mi_token}, |
| 143 | + authority=DEFAULT_TOKEN_AUTHORITY.format(tenant_id=tenant_id), |
| 144 | + ) |
| 145 | + |
| 146 | + token_res: dict[str, Any] = await asyncio.to_thread( |
| 147 | + lambda: confidential_client.acquire_token_for_client([scope]) |
| 148 | + ) |
| 149 | + |
| 150 | + return self._handle_token_response(token_res, error_prefix="FIC Step 2 failed") |
113 | 151 |
|
| 152 | + async def _acquire_managed_identity_token(self, credentials: FederatedIdentityCredentials) -> str: |
| 153 | + """Acquire managed identity token for federated identity credentials.""" |
| 154 | + # Use shared method to get or create the managed identity client |
| 155 | + mi_client = self._get_managed_identity_client(credentials) |
| 156 | + |
| 157 | + mi_token_res: dict[str, Any] = await asyncio.to_thread( |
| 158 | + lambda: mi_client.acquire_token_for_client(resource="api://AzureADTokenExchange") |
| 159 | + ) |
| 160 | + |
| 161 | + if not mi_token_res.get("access_token"): |
| 162 | + self._logger.error("FIC Step 1 failed: Could not acquire MI token") |
| 163 | + error = mi_token_res.get("error", ValueError("Error retrieving MI token")) |
| 164 | + if not isinstance(error, BaseException): |
| 165 | + error = ValueError(error) |
| 166 | + raise error |
| 167 | + |
| 168 | + return mi_token_res["access_token"] |
| 169 | + |
| 170 | + async def _get_token_with_token_provider( |
| 171 | + self, |
| 172 | + credentials: TokenCredentials, |
| 173 | + scope: str, |
| 174 | + tenant_id: str, |
| 175 | + ) -> TokenProtocol: |
| 176 | + """Get token using custom token provider function.""" |
| 177 | + token = credentials.token(scope, tenant_id) |
| 178 | + |
| 179 | + if isawaitable(token): |
| 180 | + access_token = await token |
| 181 | + else: |
| 182 | + access_token = token |
| 183 | + |
| 184 | + return JsonWebToken(access_token) |
| 185 | + |
| 186 | + def _handle_token_response(self, token_res: dict[str, Any], error_prefix: str = "") -> TokenProtocol: |
| 187 | + """Handle token response from MSAL client.""" |
| 188 | + if token_res.get("access_token", None): |
| 189 | + access_token = token_res["access_token"] |
114 | 190 | return JsonWebToken(access_token) |
| 191 | + else: |
| 192 | + error_msg = f"{error_prefix}: " if error_prefix else "" |
| 193 | + self._logger.error(f"{error_msg}Could not acquire access token") |
| 194 | + self._logger.debug(f"TokenRes: {token_res}") |
| 195 | + |
| 196 | + error = token_res.get("error", "Error retrieving token") |
| 197 | + if not isinstance(error, BaseException): |
| 198 | + error = ValueError(error) |
| 199 | + |
| 200 | + error_description = token_res.get("error_description", "Error retrieving token from MSAL") |
| 201 | + self._logger.error(error_description) |
| 202 | + raise error |
| 203 | + |
| 204 | + def _get_confidential_client(self, credentials: ClientCredentials, tenant_id: str) -> ConfidentialClientApplication: |
| 205 | + """Get or create ConfidentialClientApplication for ClientCredentials.""" |
| 206 | + # Check if client already exists in cache |
| 207 | + cached_client = self._confidential_clients_by_tenant.get(tenant_id) |
| 208 | + if cached_client: |
| 209 | + return cached_client |
| 210 | + |
| 211 | + client: ConfidentialClientApplication = ConfidentialClientApplication( |
| 212 | + credentials.client_id, |
| 213 | + client_credential=credentials.client_secret, |
| 214 | + authority=f"https://login.microsoftonline.com/{tenant_id}", |
| 215 | + ) |
| 216 | + self._confidential_clients_by_tenant[tenant_id] = client |
| 217 | + return client |
115 | 218 |
|
116 | | - def _get_msal_client(self, tenant_id: str) -> ConfidentialClientApplication | ManagedIdentityClient: |
117 | | - credentials = self._credentials |
| 219 | + def _get_managed_identity_client( |
| 220 | + self, credentials: ManagedIdentityCredentials | FederatedIdentityCredentials |
| 221 | + ) -> ManagedIdentityClient: |
| 222 | + """Get or create ManagedIdentityClient for ManagedIdentityCredentials or FederatedIdentityCredentials.""" |
| 223 | + # Check if client already exists in cache |
118 | 224 |
|
119 | | - # Create the appropriate client based on credential type |
120 | | - if isinstance(credentials, ClientCredentials): |
121 | | - # Check if client already exists in cache for this tenant |
122 | | - cached_client = self._confidential_clients_by_tenant.get(tenant_id) |
123 | | - if cached_client: |
124 | | - return cached_client |
125 | | - |
126 | | - client: ConfidentialClientApplication = ConfidentialClientApplication( |
127 | | - credentials.client_id, |
128 | | - client_credential=credentials.client_secret, |
129 | | - authority=f"https://login.microsoftonline.com/{tenant_id}", |
130 | | - ) |
131 | | - self._confidential_clients_by_tenant[tenant_id] = client |
132 | | - return client |
133 | | - elif isinstance(credentials, ManagedIdentityCredentials): |
134 | | - # ManagedIdentityClient is tenant-agnostic, cache single instance |
135 | | - if self._managed_identity_client: |
136 | | - return self._managed_identity_client |
| 225 | + # ManagedIdentityClient is tenant-agnostic, cache single instance |
| 226 | + if self._managed_identity_client: |
| 227 | + return self._managed_identity_client |
137 | 228 |
|
138 | | - # Create user-assigned managed identity |
| 229 | + # Determine managed identity type |
| 230 | + if isinstance(credentials, FederatedIdentityCredentials): |
| 231 | + if credentials.managed_identity_type == "system": |
| 232 | + managed_identity = SystemAssignedManagedIdentity() |
| 233 | + else: # "user" |
| 234 | + mi_client_id = credentials.managed_identity_client_id or credentials.client_id |
| 235 | + managed_identity = UserAssignedManagedIdentity(client_id=mi_client_id) |
| 236 | + else: # ManagedIdentityCredentials |
| 237 | + # ManagedIdentityCredentials only supports user-assigned |
139 | 238 | managed_identity = UserAssignedManagedIdentity(client_id=credentials.client_id) |
140 | 239 |
|
141 | | - self._managed_identity_client = ManagedIdentityClient( |
142 | | - managed_identity, |
143 | | - http_client=requests.Session(), |
144 | | - ) |
145 | | - return self._managed_identity_client |
146 | | - else: |
147 | | - raise ValueError(f"Unsupported credential type: {type(credentials)}") |
| 240 | + self._managed_identity_client = ManagedIdentityClient( |
| 241 | + managed_identity, |
| 242 | + http_client=requests.Session(), |
| 243 | + ) |
| 244 | + return self._managed_identity_client |
148 | 245 |
|
149 | 246 | def _resolve_tenant_id(self, tenant_id: str | None, default_tenant_id: str): |
150 | 247 | return tenant_id or (self._credentials.tenant_id if self._credentials else False) or default_tenant_id |
0 commit comments