Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
77 commits
Select commit Hold shift + click to select a range
d0fcdff
Update changelog (#35929)
xiangyan99 Jun 5, 2024
8c581a2
Autoinstrumentation rework (#35890)
jeremydvoss Jun 5, 2024
72919a9
switch to majority entra auth for tests (#35581)
kristapratico Jun 6, 2024
428ccf2
add a new parameter allow_roleassignment_on_rg to allow/disallow role…
wenjie1070116 Jun 6, 2024
61138a7
Increment package version after release of azure-core (#35950)
azure-sdk Jun 6, 2024
e6f98bc
[Event Hubs] Update URI used for consumer auth to include consumer gr…
swathipil Jun 6, 2024
697a9bf
Allow configuration of metric Views in distro (#35932)
lzchen Jun 6, 2024
bf4ee7f
[EventHub] Update README for enable logging section (#35955)
swathipil Jun 6, 2024
215bb40
[Storage] [STG 94] Merge STG 94 into `main` branch (#35888)
weirongw23-msft Jun 6, 2024
6e6648a
Sync eng/common directory with azure-sdk-tools for PR 8377 (#35915)
azure-sdk Jun 6, 2024
a73ca09
Distro release 1.6.0 (#35935)
jeremydvoss Jun 6, 2024
ae48eea
Python client for Model-as-a-Service (MaaS) / Model-as-a-Platform (Ma…
dargilco Jun 7, 2024
610da5d
[AutoRelease] t2-datafactory-2024-06-03-75602(can only be merged by S…
azure-sdk Jun 7, 2024
5b30781
Use DOTNET_ROLL_FORWARD: 'Major' for test-proxy (#35956)
azure-sdk Jun 7, 2024
acd606f
Pin pester version to 5.5.0 (#35967)
azure-sdk Jun 7, 2024
6bb9e47
Some minor updates to package & samples README.md files (#35971)
dargilco Jun 7, 2024
0b99ee1
add aoai assistants streaming/v2 tests (#35443)
kristapratico Jun 7, 2024
9b98575
[Identity] Allow use of client assertion in OBO cred (#35812)
pvaneck Jun 7, 2024
984542f
[Identity] Disable live service principal tests (#35958)
pvaneck Jun 7, 2024
a7cb46a
set storage account access to identity-based for feature store creati…
runhli Jun 7, 2024
9b6427c
Change Workspace related PR reviewer (#35921)
debuggerXi Jun 10, 2024
8abbc26
[EG] GA Namespaces (#35831)
l0lawrence Jun 10, 2024
f24b567
Increment package version after release of azure-monitor-opentelemetr…
azure-sdk Jun 10, 2024
c9b1e27
update test for new structure of custom blocklist (#36001)
kristapratico Jun 10, 2024
ec8190c
Update github-event-processor to 1.0.0-dev.20240610.2 (#36000)
azure-sdk Jun 10, 2024
81de947
[Identity] Minor doc updates (#35974)
pvaneck Jun 10, 2024
2ac0060
allow for futher embedded snippets (#36004)
l0lawrence Jun 10, 2024
40cf085
[Monitor Query + Ingestions] Update changelogs (#35942)
pvaneck Jun 10, 2024
cb065ac
[Identity] Managed identity bug fix (#36010)
pvaneck Jun 10, 2024
fe0e014
Added release dates (#36006)
vincenttran-msft Jun 10, 2024
5b55203
Remove MayankKumar91 (#35911)
lmazuel Jun 10, 2024
adbac73
Increment package version after release of azure-identity (#36015)
azure-sdk Jun 10, 2024
10c3c79
Always run analyze weekly (#35968)
kristapratico Jun 11, 2024
433b99a
move samples (#35966)
l0lawrence Jun 11, 2024
4356326
[Key Vault] Change location for weekly China cloud tests (#36018)
mccoyp Jun 11, 2024
5fd14fe
Fix Sphinx on azure-storage-blob-changefeed (#35975)
Jun 11, 2024
dff6744
update release date (#36028)
l0lawrence Jun 11, 2024
b052da8
azure-mgmt-core shouldn't use mgmt docs build (#35936)
kristapratico Jun 11, 2024
d97ff44
Identity credential unavailable error non json imds (#36016)
xiangyan99 Jun 11, 2024
e08b3b0
Update azure-ai-inference client library to support sending images as…
dargilco Jun 11, 2024
cf49b4e
Export InputTypes from constants (#35848)
emepetres Jun 11, 2024
a79c5ab
[EG] Eventgrid Release (#36030)
l0lawrence Jun 11, 2024
47fdf5d
Fix Sphinx on azure-storage-blob (#36014)
Jun 11, 2024
1552259
[Identity] Update AzurePipelinesCredential (#35858)
pvaneck Jun 11, 2024
01fa69c
upgrade autorest.python to `6.13.19` (#36024)
msyyc Jun 12, 2024
215eb63
Increment version for monitor releases (#36036)
azure-sdk Jun 12, 2024
bfd541b
compatible with new date format (#36049)
msyyc Jun 12, 2024
5b61bd4
[AutoRelease] t2-cdn-2024-06-12-45722(can only be merged by SDK owner…
azure-sdk Jun 12, 2024
614a928
[EG] link + patch update (#36045)
l0lawrence Jun 12, 2024
80ecdfb
async with (#36060)
l0lawrence Jun 12, 2024
2aba54e
Incremental (#36040)
vincenttran-msft Jun 12, 2024
379cfd3
typo (#36062)
l0lawrence Jun 12, 2024
c5e1659
Fix prepare-pipelines line wrapping (#36061)
azure-sdk Jun 12, 2024
fda24bd
[bct] Initial refactoring breaking changes tool (#36005)
catalinaperalta Jun 12, 2024
a642e74
Update swagger_to_sdk_config_dpg.json (#36068)
msyyc Jun 13, 2024
3ce8196
Increment package version after release of azure-eventgrid (#36063)
azure-sdk Jun 13, 2024
66d5de4
Sync eng/common directory with azure-sdk-tools for PR 8388 (#35970)
azure-sdk Jun 13, 2024
15bcb99
report number of breaking changes (#36067)
catalinaperalta Jun 13, 2024
0f27374
update codeowner (#36074)
xiangyan99 Jun 13, 2024
d7bfdb0
update strict-sphinx to v7 (#36075)
kristapratico Jun 13, 2024
df9c8c7
Update spelling dependencies (#36084)
azure-sdk Jun 14, 2024
3e7dff6
[DevCenter] Update release date (#36083)
drielenr Jun 14, 2024
147746b
[Identity] Add TSG section for AzurePipelinesCredential (#36048)
pvaneck Jun 14, 2024
c19f701
Support sending image data as part of a user message, using a new Ima…
dargilco Jun 14, 2024
ee65563
update (#36051)
msyyc Jun 14, 2024
892881a
Increment package version after release of azure-ai-inference (#36091)
azure-sdk Jun 14, 2024
c6383aa
address API review comments (#36058)
Adarsh-Ramanathan Jun 14, 2024
811dc0e
Update CodeownersLinter version to 1.0.0-dev.20240614.4 (#36093)
azure-sdk Jun 14, 2024
fe435b7
[AutoRelease] t2-mobilenetwork-2024-06-05-65505(can only be merged by…
azure-sdk Jun 17, 2024
a566320
[AutoRelease] t2-storagemover-2024-06-11-87054(can only be merged by …
azure-sdk Jun 17, 2024
698cd95
code and test (#35959)
azure-sdk Jun 17, 2024
40a2625
[AutoRelease] t2-web-2024-06-07-57417(can only be merged by SDK owner…
azure-sdk Jun 17, 2024
3c833e1
Update breaking_changes_allowlist.py (#36104)
msyyc Jun 17, 2024
323fdc7
appconfig mi test (#35842)
xiangyan99 Jun 17, 2024
c51ac91
Bugfix: None was being appended to output path for batch-endpoint inv…
nagkumar91 Jun 17, 2024
cd1725e
Sync eng/common directory with azure-sdk-tools for PR 8457 (#36113)
azure-sdk Jun 17, 2024
d791bc6
Merge branch 'main' into 1.17.0-core-main-merge
MilesHolland Jun 17, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
[Identity] Allow use of client assertion in OBO cred (#35812)
The new kwarg `client_assertion_func` was added to allow passing in client assertion
callbacks to OBO credential.

Signed-off-by: Paul Van Eck <[email protected]>
  • Loading branch information
pvaneck authored Jun 7, 2024
commit 9b985756ac5fe7e040cd375e1db3a1f1df879538
6 changes: 1 addition & 5 deletions sdk/identity/azure-identity/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@

### Features Added

### Breaking Changes

### Bugs Fixed

### Other Changes
- `OnBehalfOfCredential` now supports client assertion callbacks through the `client_assertion_func` keyword argument. This enables authenticating with client assertions such as federated credentials. ([#35812](https://github.com/Azure/azure-sdk-for-python/pull/35812))

## 1.17.0b1 (2024-05-13)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# Licensed under the MIT License.
# ------------------------------------
import time
from typing import Any, Optional
from typing import Any, Optional, Callable, Union, Dict

import msal

Expand All @@ -28,14 +28,18 @@ class OnBehalfOfCredential(MsalCredential, GetTokenMixin):
description of the on-behalf-of flow.

:param str tenant_id: ID of the service principal's tenant. Also called its "directory" ID.
:param str client_id: The service principal's client ID
:param str client_id: The service principal's client ID.
:keyword str client_secret: Optional. A client secret to authenticate the service principal.
Either **client_secret** or **client_certificate** must be provided.
One of **client_secret**, **client_certificate**, or **client_assertion_func** must be provided.
:keyword bytes client_certificate: Optional. The bytes of a certificate in PEM or PKCS12 format including
the private key to authenticate the service principal. Either **client_secret** or **client_certificate** must
be provided.
the private key to authenticate the service principal. One of **client_secret**, **client_certificate**,
or **client_assertion_func** must be provided.
:keyword client_assertion_func: Optional. Function that returns client assertions that authenticate the
application to Microsoft Entra ID. This function is called each time the credential requests a token. It must
return a valid assertion for the target resource.
:paramtype client_assertion_func: Callable[[], str]
:keyword str user_assertion: Required. The access token the credential will use as the user assertion when
requesting on-behalf-of tokens
requesting on-behalf-of tokens.

:keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com",
the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts`
Expand Down Expand Up @@ -65,14 +69,31 @@ class OnBehalfOfCredential(MsalCredential, GetTokenMixin):
:caption: Create an OnBehalfOfCredential.
"""

def __init__(self, tenant_id: str, client_id: str, **kwargs: Any) -> None:
self._assertion = kwargs.pop("user_assertion", None)
def __init__(
self,
tenant_id: str,
client_id: str,
*,
client_certificate: Optional[bytes] = None,
client_secret: Optional[str] = None,
client_assertion_func: Optional[Callable[[], str]] = None,
user_assertion: str,
**kwargs: Any
) -> None:
self._assertion = user_assertion
if not self._assertion:
raise TypeError('"user_assertion" is required.')
client_certificate = kwargs.pop("client_certificate", None)
client_secret = kwargs.pop("client_secret", None)
raise TypeError('"user_assertion" must not be empty.')

if client_certificate:
if client_assertion_func:
if client_certificate or client_secret:
raise ValueError(
"It is invalid to specify more than one of the following: "
'"client_assertion_func", "client_certificate" or "client_secret".'
)
credential: Union[str, Dict[str, Any]] = {
"client_assertion": client_assertion_func,
}
elif client_certificate:
if client_secret:
raise ValueError('Specifying both "client_certificate" and "client_secret" is not valid.')
try:
Expand All @@ -86,7 +107,7 @@ def __init__(self, tenant_id: str, client_id: str, **kwargs: Any) -> None:
elif client_secret:
credential = client_secret
else:
raise TypeError('Either "client_certificate" or "client_secret" must be provided')
raise TypeError('Either "client_certificate", "client_secret", or "client_assertion_func" must be provided')

super(OnBehalfOfCredential, self).__init__(
client_id=client_id, client_credential=credential, tenant_id=tenant_id, **kwargs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ def _get_client_secret_request(self, scopes: Iterable[str], secret: str, **kwarg
def _get_on_behalf_of_request(
self,
scopes: Iterable[str],
client_credential: Union[str, AadClientCertificate],
client_credential: Union[str, AadClientCertificate, Dict[str, Any]],
user_assertion: str,
**kwargs: Any
) -> HttpRequest:
Expand All @@ -288,6 +288,10 @@ def _get_on_behalf_of_request(
if isinstance(client_credential, AadClientCertificate):
data["client_assertion"] = self._get_client_certificate_assertion(client_credential)
data["client_assertion_type"] = JWT_BEARER_ASSERTION
elif isinstance(client_credential, dict):
func = client_credential["client_assertion"]
data["client_assertion"] = func()
data["client_assertion_type"] = JWT_BEARER_ASSERTION
else:
data["client_secret"] = client_credential

Expand Down Expand Up @@ -318,7 +322,7 @@ def _get_refresh_token_request(self, scopes: Iterable[str], refresh_token: str,
def _get_refresh_token_on_behalf_of_request(
self,
scopes: Iterable[str],
client_credential: Union[str, AadClientCertificate],
client_credential: Union[str, AadClientCertificate, Dict[str, Any]],
refresh_token: str,
**kwargs: Any
) -> HttpRequest:
Expand All @@ -338,6 +342,10 @@ def _get_refresh_token_on_behalf_of_request(
if isinstance(client_credential, AadClientCertificate):
data["client_assertion"] = self._get_client_certificate_assertion(client_credential)
data["client_assertion_type"] = JWT_BEARER_ASSERTION
elif isinstance(client_credential, dict):
func = client_credential["client_assertion"]
data["client_assertion"] = func()
data["client_assertion_type"] = JWT_BEARER_ASSERTION
else:
data["client_secret"] = client_credential
request = self._post(data, **kwargs)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class MsalCredential: # pylint: disable=too-many-instance-attributes
def __init__(
self,
client_id: str,
client_credential: Optional[Union[str, Dict[str, str]]] = None,
client_credential: Optional[Union[str, Dict[str, Any]]] = None,
*,
additionally_allowed_tenants: Optional[List[str]] = None,
authority: Optional[str] = None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# Licensed under the MIT License.
# ------------------------------------
import logging
from typing import Optional, Union, Any
from typing import Optional, Union, Any, Dict, Callable

from azure.core.exceptions import ClientAuthenticationError
from azure.core.credentials import AccessToken
Expand All @@ -25,14 +25,18 @@ class OnBehalfOfCredential(AsyncContextManager, GetTokenMixin):
description of the on-behalf-of flow.

:param str tenant_id: ID of the service principal's tenant. Also called its "directory" ID.
:param str client_id: The service principal's client ID
:param str client_id: The service principal's client ID.
:keyword str client_secret: Optional. A client secret to authenticate the service principal.
Either **client_secret** or **client_certificate** must be provided.
One of **client_secret**, **client_certificate**, or **client_assertion_func** must be provided.
:keyword bytes client_certificate: Optional. The bytes of a certificate in PEM or PKCS12 format including
the private key to authenticate the service principal. Either **client_secret** or **client_certificate** must
be provided.
the private key to authenticate the service principal. One of **client_secret**, **client_certificate**,
or **client_assertion_func** must be provided.
:keyword client_assertion_func: Optional. Function that returns client assertions that authenticate the
application to Microsoft Entra ID. This function is called each time the credential requests a token. It must
return a valid assertion for the target resource.
:paramtype client_assertion_func: Callable[[], str]
:keyword str user_assertion: Required. The access token the credential will use as the user assertion when
requesting on-behalf-of tokens
requesting on-behalf-of tokens.

:keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com",
the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts`
Expand Down Expand Up @@ -62,29 +66,39 @@ def __init__(
*,
client_certificate: Optional[bytes] = None,
client_secret: Optional[str] = None,
client_assertion_func: Optional[Callable[[], str]] = None,
user_assertion: str,
**kwargs: Any
) -> None:
super().__init__()
validate_tenant_id(tenant_id)

self._assertion = user_assertion

if client_certificate:
if not self._assertion:
raise TypeError('"user_assertion" must not be empty.')

if client_assertion_func:
if client_certificate or client_secret:
raise ValueError(
"It is invalid to specify more than one of the following: "
'"client_assertion_func", "client_certificate" or "client_secret".'
)
self._client_credential: Union[str, AadClientCertificate, Dict[str, Any]] = {
"client_assertion": client_assertion_func,
}
elif client_certificate:
if client_secret:
raise ValueError('Specifying both "client_certificate" and "client_secret" is not valid.')
try:
cert = get_client_credential(None, kwargs.pop("password", None), client_certificate)
except ValueError as ex:
message = '"client_certificate" is not a valid certificate in PEM or PKCS12 format'
raise ValueError(message) from ex
self._client_credential: Union[str, AadClientCertificate] = AadClientCertificate(
cert["private_key"], password=cert.get("passphrase")
)
self._client_credential = AadClientCertificate(cert["private_key"], password=cert.get("passphrase"))
elif client_secret:
self._client_credential = client_secret
else:
raise TypeError('Either "client_certificate" or "client_secret" must be provided')
raise TypeError('Either "client_certificate", "client_secret", or "client_assertion_func" must be provided')

# note AadClient handles "authority" and any pipeline kwargs
self._client = AadClient(tenant_id, client_id, **kwargs)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# Licensed under the MIT License.
# ------------------------------------
import time
from typing import Iterable, Optional, Union
from typing import Iterable, Optional, Union, Dict, Any

from azure.core.credentials import AccessToken
from azure.core.pipeline import AsyncPipeline
Expand Down Expand Up @@ -57,15 +57,23 @@ async def obtain_token_by_refresh_token(self, scopes: Iterable[str], refresh_tok
return await self._run_pipeline(request, **kwargs)

async def obtain_token_by_refresh_token_on_behalf_of( # pylint: disable=name-too-long
self, scopes: Iterable[str], client_credential: Union[str, AadClientCertificate], refresh_token: str, **kwargs
self,
scopes: Iterable[str],
client_credential: Union[str, AadClientCertificate, Dict[str, Any]],
refresh_token: str,
**kwargs
) -> AccessToken:
request = self._get_refresh_token_on_behalf_of_request(
scopes, client_credential=client_credential, refresh_token=refresh_token, **kwargs
)
return await self._run_pipeline(request, **kwargs)

async def obtain_token_on_behalf_of(
self, scopes: Iterable[str], client_credential: Union[str, AadClientCertificate], user_assertion: str, **kwargs
self,
scopes: Iterable[str],
client_credential: Union[str, AadClientCertificate, Dict[str, Any]],
user_assertion: str,
**kwargs
) -> AccessToken:
request = self._get_on_behalf_of_request(
scopes=scopes, client_credential=client_credential, user_assertion=user_assertion, **kwargs
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
"""
FILE: on_behalf_of_client_assertion.py
DESCRIPTION:
This sample demonstrates the use of OnBehalfOfCredential to authenticate the Key Vault SecretClient using a managed
identity as the client assertion. More information about the On-Behalf-Of flow can be found here:
https://learn.microsoft.com/entra/identity-platform/v2-oauth2-on-behalf-of-flow.
USAGE:
python on_behalf_of_client_assertion.py

**Note** - This sample requires the `azure-keyvault-secrets` package.
"""
# [START obo_client_assertion]
from azure.identity import OnBehalfOfCredential, ManagedIdentityCredential
from azure.keyvault.secrets import SecretClient


# Replace the following variables with your own values.
tenant_id = "<tenant_id>"
client_id = "<client_id>"
user_assertion = "<user_assertion>"

managed_identity_credential = ManagedIdentityCredential()


def get_managed_identity_token() -> str:
# This function should return an access token obtained from a managed identity.
access_token = managed_identity_credential.get_token("api://AzureADTokenExchange")
return access_token.token


credential = OnBehalfOfCredential(
tenant_id=tenant_id,
client_id=client_id,
user_assertion=user_assertion,
client_assertion_func=get_managed_identity_token,
)

client = SecretClient(vault_url="https://<your-key-vault-name>.vault.azure.net/", credential=credential)
# [END obo_client_assertion]
51 changes: 51 additions & 0 deletions sdk/identity/azure-identity/tests/test_obo.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from azure.core.pipeline.policies import ContentDecodePolicy, SansIOHTTPPolicy
from azure.identity import OnBehalfOfCredential, UsernamePasswordCredential
from azure.identity._constants import EnvironmentVariables
from azure.identity._internal.aad_client_base import JWT_BEARER_ASSERTION
from azure.identity._internal.user_agent import USER_AGENT
import pytest
from urllib.parse import urlparse
Expand Down Expand Up @@ -228,3 +229,53 @@ def test_no_client_credential():
"""The credential should raise ValueError when ctoring with no client_secret or client_certificate"""
with pytest.raises(TypeError):
credential = OnBehalfOfCredential("tenant-id", "client-id", user_assertion="assertion")


def test_client_assertion_func():
"""The credential should accept a client_assertion_func"""
expected_client_assertion = "client-assertion"
expected_user_assertion = "user-assertion"
expected_token = "***"
func_call_count = 0

def client_assertion_func():
nonlocal func_call_count
func_call_count += 1
return expected_client_assertion

def send(request, **kwargs):
parsed = urlparse(request.url)
tenant = parsed.path.split("/")[1]
if "/oauth2/v2.0/token" not in parsed.path:
return get_discovery_response("https://{}/{}".format(parsed.netloc, tenant))

assert request.data.get("client_assertion") == expected_client_assertion
assert request.data.get("client_assertion_type") == JWT_BEARER_ASSERTION
assert request.data.get("assertion") == expected_user_assertion
return mock_response(json_payload=build_aad_response(access_token=expected_token))

transport = Mock(send=Mock(wraps=send))
credential = OnBehalfOfCredential(
"tenant-id",
"client-id",
client_assertion_func=client_assertion_func,
user_assertion=expected_user_assertion,
transport=transport,
)

access_token = credential.get_token("scope")
assert access_token.token == expected_token
assert func_call_count == 1


def test_client_assertion_func_with_client_certificate():
"""The credential should raise ValueError when ctoring with both client_assertion_func and client_certificate"""
with pytest.raises(ValueError) as ex:
credential = OnBehalfOfCredential(
"tenant-id",
"client-id",
client_assertion_func=lambda: "client-assertion",
client_certificate=b"certificate",
user_assertion="assertion",
)
assert "It is invalid to specify more than one of the following" in str(ex.value)
Loading