-
Notifications
You must be signed in to change notification settings - Fork 2.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Token exchange support for ManagedIdentityCredential #19902
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
04ae08e
ClientAssertionCredential (internal)
chlowell c0e85fc
TokenExchangeCredential (also internal)
chlowell 07feea8
update ManagedIdentityCredential
chlowell 61650cd
tests
chlowell c3e1c40
shorten lines
chlowell ab02814
assume TokenExchangeCredential used only by ManagedIdentityCredential
chlowell 45ae1d4
correct docstring
chlowell a66e926
simplify TokenExchangeCredential
chlowell b6b4a57
remove context manager API from internal class
chlowell ce4c730
TokenExchangeCredential is more upfront about its parameters
chlowell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
45 changes: 45 additions & 0 deletions
45
sdk/identity/azure-identity/azure/identity/_credentials/client_assertion.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
# ------------------------------------ | ||
# Copyright (c) Microsoft Corporation. | ||
# Licensed under the MIT License. | ||
# ------------------------------------ | ||
from typing import TYPE_CHECKING | ||
|
||
from .._internal import AadClient | ||
from .._internal.get_token_mixin import GetTokenMixin | ||
|
||
if TYPE_CHECKING: | ||
from typing import Any, Callable, Optional | ||
from azure.core.credentials import AccessToken | ||
|
||
|
||
class ClientAssertionCredential(GetTokenMixin): | ||
def __init__(self, tenant_id, client_id, get_assertion, **kwargs): | ||
# type: (str, str, Callable[[], str], **Any) -> None | ||
"""Authenticates a service principal with a JWT assertion. | ||
This credential is for advanced scenarios. :class:`~azure.identity.ClientCertificateCredential` has a more | ||
convenient API for the most common assertion scenario, authenticating a service principal with a certificate. | ||
:param str tenant_id: ID of the principal's tenant. Also called its "directory" ID. | ||
:param str client_id: the principal's client ID | ||
:param get_assertion: a callable that returns a string assertion. The credential will call this every time it | ||
acquires a new token. | ||
:paramtype get_assertion: Callable[[], str] | ||
:keyword str authority: authority of an Azure Active Directory endpoint, for example | ||
"login.microsoftonline.com", the authority for Azure Public Cloud (which is the default). | ||
:class:`~azure.identity.AzureAuthorityHosts` defines authorities for other clouds. | ||
""" | ||
self._get_assertion = get_assertion | ||
self._client = AadClient(tenant_id, client_id, **kwargs) | ||
super(ClientAssertionCredential, self).__init__(**kwargs) | ||
|
||
def _acquire_token_silently(self, *scopes, **kwargs): | ||
# type: (*str, **Any) -> Optional[AccessToken] | ||
return self._client.get_cached_access_token(scopes, **kwargs) | ||
|
||
def _request_token(self, *scopes, **kwargs): | ||
# type: (*str, **Any) -> AccessToken | ||
assertion = self._get_assertion() | ||
token = self._client.obtain_token_by_jwt_assertion(scopes, assertion, **kwargs) | ||
return token |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
42 changes: 42 additions & 0 deletions
42
sdk/identity/azure-identity/azure/identity/_credentials/token_exchange.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
# ------------------------------------ | ||
# Copyright (c) Microsoft Corporation. | ||
# Licensed under the MIT License. | ||
# ------------------------------------ | ||
import time | ||
from typing import TYPE_CHECKING | ||
|
||
from .client_assertion import ClientAssertionCredential | ||
|
||
if TYPE_CHECKING: | ||
# pylint:disable=unused-import,ungrouped-imports | ||
from typing import Any | ||
|
||
|
||
class TokenFileMixin(object): | ||
def __init__(self, token_file_path, **_): | ||
# type: (str, **Any) -> None | ||
super(TokenFileMixin, self).__init__() | ||
self._jwt = "" | ||
self._last_read_time = 0 | ||
self._token_file_path = token_file_path | ||
|
||
def get_service_account_token(self): | ||
# type: () -> str | ||
now = int(time.time()) | ||
if now - self._last_read_time > 300: | ||
with open(self._token_file_path) as f: | ||
self._jwt = f.read() | ||
self._last_read_time = now | ||
return self._jwt | ||
|
||
|
||
class TokenExchangeCredential(ClientAssertionCredential, TokenFileMixin): | ||
def __init__(self, tenant_id, client_id, token_file_path, **kwargs): | ||
# type: (str, str, str, **Any) -> None | ||
super(TokenExchangeCredential, self).__init__( | ||
tenant_id=tenant_id, | ||
client_id=client_id, | ||
get_assertion=self.get_service_account_token, | ||
token_file_path=token_file_path, | ||
**kwargs | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
50 changes: 50 additions & 0 deletions
50
sdk/identity/azure-identity/azure/identity/aio/_credentials/client_assertion.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
# ------------------------------------ | ||
# Copyright (c) Microsoft Corporation. | ||
# Licensed under the MIT License. | ||
# ------------------------------------ | ||
from typing import TYPE_CHECKING | ||
|
||
from .._internal import AadClient, AsyncContextManager | ||
from .._internal.get_token_mixin import GetTokenMixin | ||
|
||
if TYPE_CHECKING: | ||
from typing import Any, Callable, Optional | ||
from azure.core.credentials import AccessToken | ||
|
||
|
||
class ClientAssertionCredential(AsyncContextManager, GetTokenMixin): | ||
def __init__(self, tenant_id: str, client_id: str, get_assertion: "Callable[[], str]", **kwargs: "Any") -> None: | ||
"""Authenticates a service principal with a JWT assertion. | ||
This credential is for advanced scenarios. :class:`~azure.identity.ClientCertificateCredential` has a more | ||
convenient API for the most common assertion scenario, authenticating a service principal with a certificate. | ||
:param str tenant_id: ID of the principal's tenant. Also called its "directory" ID. | ||
:param str client_id: the principal's client ID | ||
:param get_assertion: a callable that returns a string assertion. The credential will call this every time it | ||
acquires a new token. | ||
:paramtype get_assertion: Callable[[], str] | ||
:keyword str authority: authority of an Azure Active Directory endpoint, for example | ||
"login.microsoftonline.com", the authority for Azure Public Cloud (which is the default). | ||
:class:`~azure.identity.AzureAuthorityHosts` defines authorities for other clouds. | ||
""" | ||
self._get_assertion = get_assertion | ||
self._client = AadClient(tenant_id, client_id, **kwargs) | ||
super().__init__(**kwargs) | ||
|
||
async def __aenter__(self): | ||
await self._client.__aenter__() | ||
return self | ||
|
||
async def close(self) -> None: | ||
"""Close the credential's transport session.""" | ||
await self._client.close() | ||
|
||
async def _acquire_token_silently(self, *scopes: str, **kwargs: "Any") -> "Optional[AccessToken]": | ||
return self._client.get_cached_access_token(scopes, **kwargs) | ||
|
||
async def _request_token(self, *scopes: str, **kwargs: "Any") -> "AccessToken": | ||
assertion = self._get_assertion() | ||
token = await self._client.obtain_token_by_jwt_assertion(scopes, assertion, **kwargs) | ||
return token |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
23 changes: 23 additions & 0 deletions
23
sdk/identity/azure-identity/azure/identity/aio/_credentials/token_exchange.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
# ------------------------------------ | ||
# Copyright (c) Microsoft Corporation. | ||
# Licensed under the MIT License. | ||
# ------------------------------------ | ||
from typing import TYPE_CHECKING | ||
|
||
from .client_assertion import ClientAssertionCredential | ||
from ..._credentials.token_exchange import TokenFileMixin | ||
|
||
if TYPE_CHECKING: | ||
# pylint:disable=unused-import,ungrouped-imports | ||
from typing import Any | ||
|
||
|
||
class TokenExchangeCredential(ClientAssertionCredential, TokenFileMixin): | ||
def __init__(self, tenant_id: str, client_id: str, token_file_path: str, **kwargs: "Any") -> None: | ||
super().__init__( | ||
tenant_id=tenant_id, | ||
client_id=client_id, | ||
get_assertion=self.get_service_account_token, | ||
token_file_path=token_file_path, | ||
**kwargs | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Are you keeping the async context management API since it's more relevant for async credentials?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That and
self._client
here already implements the API. I removed it from the sync credential because I don't want to block this PR on #19746 or paste part of that PR into this one.