-
Notifications
You must be signed in to change notification settings - Fork 3.3k
identity broker package #32360
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
Merged
Merged
identity broker package #32360
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
3f9ddb6
identity broker package
xiangyan99 5544a78
update
xiangyan99 adf61b9
update
xiangyan99 c419cbe
black
xiangyan99 9cea357
update
xiangyan99 043420a
update
xiangyan99 4aaf364
update
xiangyan99 16d1b26
update
xiangyan99 8611f14
update
xiangyan99 b349408
update
xiangyan99 8dc4bab
update
xiangyan99 364ada3
update
xiangyan99 d4bda7d
update
xiangyan99 be70c71
Update sdk/identity/azure-identity-broker/MANIFEST.in
xiangyan99 f3441d1
Update sdk/identity/azure-identity-broker/azure/identity/broker/_user…
xiangyan99 29025f1
Update sdk/identity/azure-identity-broker/azure/identity/broker/_user…
xiangyan99 c81e562
Update sdk/identity/azure-identity-broker/azure/identity/broker/_brow…
xiangyan99 0c1f98d
update
xiangyan99 b1943e3
update
xiangyan99 aa03437
Update sdk/identity/azure-identity-broker/azure/identity/broker/_brow…
xiangyan99 00dc9fb
Update sdk/identity/azure-identity-broker/azure/identity/broker/_brow…
xiangyan99 d40557a
update
xiangyan99 3c8bbd7
update
xiangyan99 d6cbc31
update
xiangyan99 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 hidden or 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 hidden or 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,14 @@ | ||
| # Release History | ||
|
|
||
| ## 1.0.0b1 (Unreleased) | ||
|
|
||
| ### Features Added | ||
|
|
||
| - Added `azure.identity.broker.InteractiveBrowserBrokerCredential` | ||
| and `azure.identity.broker.UsernamePasswordBrokerCredential` which have broker support. | ||
|
|
||
| ### Breaking Changes | ||
|
|
||
| ### Bugs Fixed | ||
|
|
||
| ### Other Changes |
This file contains hidden or 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,21 @@ | ||
| Copyright (c) Microsoft Corporation. | ||
|
|
||
| MIT License | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
|
|
||
| THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. |
This file contains hidden or 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,6 @@ | ||
| recursive-include samples *.py | ||
| recursive-include tests *.py | ||
| include *.md | ||
| include LICENSE | ||
| include azure/__init__.py | ||
| include azure/identity/broker/py.typed |
This file contains hidden or 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,43 @@ | ||
|
|
||
|
|
||
| # Azure Identity Broker plugin for Python | ||
|
|
||
| ## Getting started | ||
|
|
||
| ### Install the package | ||
|
|
||
| Install the Azure Identity Broker plugin for Python with [pip](https://pypi.org/project/pip/): | ||
|
|
||
| ```bash | ||
| pip install azure-identity-broker | ||
| ``` | ||
|
|
||
|
|
||
| ## Examples | ||
|
|
||
| Now you can create `azure.identity.broker.InteractiveBrowserCredential` and `azure.identity.broker.UsernamePasswordCredential` with broker support. | ||
|
|
||
| ```python | ||
|
|
||
| import win32gui | ||
| from azure.identity.broker import InteractiveBrowserCredential | ||
|
|
||
| # Get the handle of the current window | ||
| current_window_handle = win32gui.GetForegroundWindow() | ||
|
|
||
| credential = InteractiveBrowserCredential(allow_broker=True, parent_window_handle=current_window_handle) | ||
| ``` | ||
|
|
||
|
|
||
| ## Troubleshooting | ||
|
|
||
| This client raises exceptions defined in [Azure Core](https://learn.microsoft.com/python/api/azure-core/azure.core.exceptions?view=azure-python). | ||
|
|
||
|
|
||
| ## Contributing | ||
|
|
||
| This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. | ||
|
|
||
| When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. | ||
|
|
||
| This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. |
This file contains hidden or 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 @@ | ||
| __path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore |
This file contains hidden or 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 @@ | ||
| __path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore |
12 changes: 12 additions & 0 deletions
12
sdk/identity/azure-identity-broker/azure/identity/broker/__init__.py
This file contains hidden or 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,12 @@ | ||
| # ------------------------------------ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
| # ------------------------------------ | ||
| from ._browser import InteractiveBrowserBrokerCredential | ||
| from ._user_password import UsernamePasswordBrokerCredential | ||
|
|
||
|
|
||
| __all__ = [ | ||
| "InteractiveBrowserBrokerCredential", | ||
| "UsernamePasswordBrokerCredential", | ||
| ] |
135 changes: 135 additions & 0 deletions
135
sdk/identity/azure-identity-broker/azure/identity/broker/_browser.py
This file contains hidden or 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,135 @@ | ||
| # ------------------------------------ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
| # ------------------------------------ | ||
| import socket | ||
| from typing import Dict, Any | ||
| import msal | ||
|
|
||
| from azure.core.exceptions import ClientAuthenticationError | ||
| from azure.identity._credentials import ( | ||
| InteractiveBrowserCredential as _InteractiveBrowserCredential, | ||
| ) # pylint:disable=protected-access | ||
| from azure.identity._exceptions import CredentialUnavailableError # pylint:disable=protected-access | ||
| from azure.identity._internal.utils import within_dac # pylint:disable=protected-access | ||
| from ._utils import wrap_exceptions, resolve_tenant | ||
|
|
||
|
|
||
| class InteractiveBrowserBrokerCredential(_InteractiveBrowserCredential): | ||
| """Opens a browser to interactively authenticate a user. | ||
|
|
||
| :func:`~get_token` opens a browser to a login URL provided by Azure Active Directory and authenticates a user | ||
| there with the authorization code flow, using PKCE (Proof Key for Code Exchange) internally to protect the code. | ||
|
|
||
| :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. | ||
| :keyword str tenant_id: an Azure Active Directory tenant ID. Defaults to the "organizations" tenant, which can | ||
| authenticate work or school accounts. | ||
| :keyword str client_id: Client ID of the Azure Active Directory application users will sign in to. If | ||
| unspecified, users will authenticate to an Azure development application. | ||
| :keyword str login_hint: a username suggestion to pre-fill the login page's username/email address field. A user | ||
| may still log in with a different username. | ||
| :keyword str redirect_uri: a redirect URI for the application identified by `client_id` as configured in Azure | ||
| Active Directory, for example "http://localhost:8400". This is only required when passing a value for | ||
| **client_id**, and must match a redirect URI in the application's registration. The credential must be able to | ||
| bind a socket to this URI. | ||
| :keyword AuthenticationRecord authentication_record: :class:`AuthenticationRecord` returned by :func:`authenticate` | ||
| :keyword bool disable_automatic_authentication: if True, :func:`get_token` will raise | ||
| :class:`AuthenticationRequiredError` when user interaction is required to acquire a token. Defaults to False. | ||
| :keyword cache_persistence_options: configuration for persistent token caching. If unspecified, the credential | ||
| will cache tokens in memory. | ||
| :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions | ||
| :keyword int timeout: seconds to wait for the user to complete authentication. Defaults to 300 (5 minutes). | ||
| :keyword bool allow_broker: An authentication broker is an application that runs on a user's machine that manages | ||
| the authentication handshakes and token maintenance for connected accounts. The Windows operating system uses | ||
| the Web Account Manager (WAM) as its authentication broker. If this parameter is set to True, the broker will | ||
| be used when possible. Defaults to False. | ||
| Check https://learn.microsoft.com/azure/active-directory/develop/scenario-desktop-acquire-token-wam for more | ||
| information about WAM. | ||
| :keyword int parent_window_handle: If your app is a GUI app running on a modern Windows system, | ||
| and your app opts in to use broker via `allow_broker`, you are required to also provide its window handle, | ||
| so that the sign in UI window will properly pop up on top of your window. | ||
| :keyword bool enable_msa_passthrough: Determines whether Microsoft Account (MSA) passthrough is enabled. Note, this | ||
| is only needed for select legacy first-party applications. Defaults to False. | ||
| :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting | ||
| to authenticate. Setting this to true will completely disable both instance discovery and authority validation. | ||
| This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in | ||
| private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from | ||
| https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the | ||
| authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and | ||
| trustworthy. | ||
| :raises ValueError: invalid **redirect_uri** | ||
| """ | ||
|
|
||
| def __init__(self, **kwargs: Any) -> None: | ||
| self._allow_broker = kwargs.pop("allow_broker", None) | ||
| self._parent_window_handle = kwargs.pop("parent_window_handle", None) | ||
| self._enable_msa_passthrough = kwargs.pop("enable_msa_passthrough", False) | ||
| super().__init__(**kwargs) | ||
|
|
||
| @wrap_exceptions | ||
| def _request_token(self, *scopes: str, **kwargs: Any) -> Dict: | ||
| scopes = list(scopes) # type: ignore | ||
| claims = kwargs.get("claims") | ||
| app = self._get_app(**kwargs) | ||
| port = self._parsed_url.port if self._parsed_url else None | ||
|
|
||
| try: | ||
| result = app.acquire_token_interactive( | ||
| scopes=scopes, | ||
| login_hint=self._login_hint, | ||
| claims_challenge=claims, | ||
| timeout=self._timeout, | ||
| prompt="select_account", | ||
| port=port, | ||
| parent_window_handle=self._parent_window_handle, | ||
| enable_msa_passthrough=self._enable_msa_passthrough, | ||
| ) | ||
| except socket.error as ex: | ||
| raise CredentialUnavailableError(message="Couldn't start an HTTP server.") from ex | ||
| if "access_token" not in result and "error_description" in result: | ||
| if within_dac.get(): | ||
| raise CredentialUnavailableError(message=result["error_description"]) | ||
| raise ClientAuthenticationError(message=result.get("error_description")) | ||
| if "access_token" not in result: | ||
| if within_dac.get(): | ||
| raise CredentialUnavailableError(message="Failed to authenticate user") | ||
| raise ClientAuthenticationError(message="Failed to authenticate user") | ||
|
|
||
| # base class will raise for other errors | ||
| return result | ||
|
|
||
| def _get_app(self, **kwargs: Any) -> msal.ClientApplication: | ||
| tenant_id = resolve_tenant( | ||
| self._tenant_id, additionally_allowed_tenants=self._additionally_allowed_tenants, **kwargs | ||
| ) | ||
|
|
||
| client_applications_map = self._client_applications | ||
| capabilities = None | ||
| token_cache = self._cache | ||
|
|
||
| app_class = msal.ConfidentialClientApplication if self._client_credential else msal.PublicClientApplication | ||
|
|
||
| if kwargs.get("enable_cae"): | ||
| client_applications_map = self._cae_client_applications | ||
| capabilities = ["CP1"] | ||
| token_cache = self._cae_cache | ||
|
|
||
| if not token_cache: | ||
| token_cache = self._initialize_cache(is_cae=bool(kwargs.get("enable_cae"))) | ||
|
|
||
| if tenant_id not in client_applications_map: | ||
| client_applications_map[tenant_id] = app_class( | ||
| client_id=self._client_id, | ||
| client_credential=self._client_credential, | ||
| client_capabilities=capabilities, | ||
| authority="{}/{}".format(self._authority, tenant_id), | ||
| azure_region=self._regional_authority, | ||
| token_cache=token_cache, | ||
| http_client=self._client, | ||
| instance_discovery=self._instance_discovery, | ||
| allow_broker=self._allow_broker, | ||
| ) | ||
|
|
||
| return client_applications_map[tenant_id] | ||
100 changes: 100 additions & 0 deletions
100
sdk/identity/azure-identity-broker/azure/identity/broker/_user_password.py
This file contains hidden or 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,100 @@ | ||
| # ------------------------------------ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
| # ------------------------------------ | ||
| from typing import Any | ||
| import msal | ||
| from azure.identity._credentials import ( | ||
| UsernamePasswordCredential as _UsernamePasswordCredential, | ||
| ) # pylint:disable=protected-access | ||
| from ._utils import resolve_tenant | ||
|
|
||
|
|
||
| class UsernamePasswordBrokerCredential(_UsernamePasswordCredential): | ||
| """Authenticates a user with a username and password. | ||
|
|
||
| In general, Microsoft doesn't recommend this kind of authentication, because it's less secure than other | ||
| authentication flows. | ||
|
|
||
| Authentication with this credential is not interactive, so it is **not compatible with any form of | ||
| multi-factor authentication or consent prompting**. The application must already have consent from the user or | ||
| a directory admin. | ||
|
|
||
| This credential can only authenticate work and school accounts; Microsoft accounts are not supported. | ||
| See `Azure Active Directory documentation | ||
| <https://docs.microsoft.com/azure/active-directory/fundamentals/sign-up-organization>`_ for more information about | ||
| account types. | ||
|
|
||
| :param str client_id: The application's client ID | ||
| :param str username: The user's username (usually an email address) | ||
| :param str password: The user's password | ||
|
|
||
| :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. | ||
| :keyword str tenant_id: Tenant ID or a domain associated with a tenant. If not provided, defaults to the | ||
| "organizations" tenant, which supports only Azure Active Directory work or school accounts. | ||
| :keyword cache_persistence_options: Configuration for persistent token caching. If unspecified, the credential | ||
| will cache tokens in memory. | ||
| :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions | ||
| :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting | ||
| to authenticate. Setting this to true will completely disable both instance discovery and authority validation. | ||
| This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in | ||
| private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from | ||
| https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the | ||
| authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and | ||
| trustworthy. | ||
| :keyword bool allow_broker: An authentication broker is an application that runs on a user's machine that manages | ||
| the authentication handshakes and token maintenance for connected accounts. The Windows operating system uses | ||
| the Web Account Manager (WAM) as its authentication broker. If this parameter is set to True, the broker will | ||
| be used when possible. Defaults to False. | ||
| Check https://learn.microsoft.com/azure/active-directory/develop/scenario-desktop-acquire-token-wam for more | ||
| information about WAM. | ||
| :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" | ||
| for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to | ||
| acquire tokens for any tenant the application can access. | ||
| """ | ||
|
|
||
| def __init__(self, client_id: str, username: str, password: str, **kwargs: Any) -> None: | ||
| # The base class will accept an AuthenticationRecord, allowing this credential to authenticate silently the | ||
| # first time it's asked for a token. However, we want to ensure this first authentication is not silent, to | ||
| # validate the given password. This class therefore doesn't document the authentication_record argument, and we | ||
| # discard it here. | ||
| self._allow_broker = kwargs.pop("allow_broker", None) | ||
| super(UsernamePasswordBrokerCredential, self).__init__( | ||
| client_id=client_id, username=username, password=password, **kwargs | ||
| ) | ||
|
|
||
| def _get_app(self, **kwargs: Any) -> msal.ClientApplication: | ||
| tenant_id = resolve_tenant( | ||
| self._tenant_id, additionally_allowed_tenants=self._additionally_allowed_tenants, **kwargs | ||
| ) | ||
|
|
||
| client_applications_map = self._client_applications | ||
| capabilities = None | ||
| token_cache = self._cache | ||
|
|
||
| app_class = msal.ConfidentialClientApplication if self._client_credential else msal.PublicClientApplication | ||
|
|
||
| if kwargs.get("enable_cae"): | ||
| client_applications_map = self._cae_client_applications | ||
| capabilities = ["CP1"] | ||
| token_cache = self._cae_cache | ||
|
|
||
| if not token_cache: | ||
| token_cache = self._initialize_cache(is_cae=bool(kwargs.get("enable_cae"))) | ||
|
|
||
| if tenant_id not in client_applications_map: | ||
| client_applications_map[tenant_id] = app_class( | ||
| client_id=self._client_id, | ||
| client_credential=self._client_credential, | ||
| client_capabilities=capabilities, | ||
| authority="{}/{}".format(self._authority, tenant_id), | ||
| azure_region=self._regional_authority, | ||
| token_cache=token_cache, | ||
| http_client=self._client, | ||
| instance_discovery=self._instance_discovery, | ||
| allow_broker=self._allow_broker, | ||
| ) | ||
|
|
||
| return client_applications_map[tenant_id] |
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.
Uh oh!
There was an error while loading. Please reload this page.