Skip to content

Commit 9962643

Browse files
committed
init
1 parent f76cfd2 commit 9962643

3 files changed

Lines changed: 28 additions & 36 deletions

File tree

src/azure-cli-core/azure/cli/core/_profile.py

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -226,59 +226,59 @@ def login_with_managed_identity(self, identity_id=None, allow_no_subscriptions=N
226226

227227
import jwt
228228
from azure.mgmt.core.tools import is_valid_resource_id
229-
from azure.cli.core.auth.adal_authentication import MSIAuthenticationWrapper
230-
resource = self.cli_ctx.cloud.endpoints.active_directory_resource_id
229+
from azure.cli.core.auth.msal_credentials import ManagedIdentityCredential
231230

232231
if identity_id:
233232
if is_valid_resource_id(identity_id):
234-
msi_creds = MSIAuthenticationWrapper(resource=resource, msi_res_id=identity_id)
233+
cred = ManagedIdentityCredential(resource_id=identity_id)
234+
cred.get_token(*self._arm_scope)
235235
identity_type = MsiAccountTypes.user_assigned_resource_id
236236
else:
237237
authenticated = False
238-
from azure.cli.core.azclierror import AzureResponseError
239238
try:
240-
msi_creds = MSIAuthenticationWrapper(resource=resource, client_id=identity_id)
239+
cred = ManagedIdentityCredential(client_id=identity_id)
240+
cred.get_token(*self._arm_scope)
241241
identity_type = MsiAccountTypes.user_assigned_client_id
242242
authenticated = True
243-
except AzureResponseError as ex:
244-
if 'http error: 400, reason: Bad Request' in ex.error_msg:
245-
logger.info('Sniff: not an MSI client id')
243+
except AuthenticationError as ex:
244+
if 'Identity not found' in ex.error_msg:
245+
logger.info('Sniff: not client id')
246246
else:
247247
raise
248248

249249
if not authenticated:
250250
try:
251+
cred = ManagedIdentityCredential(object_id=identity_id)
252+
cred.get_token(*self._arm_scope)
251253
identity_type = MsiAccountTypes.user_assigned_object_id
252-
msi_creds = MSIAuthenticationWrapper(resource=resource, object_id=identity_id)
253254
authenticated = True
254-
except AzureResponseError as ex:
255-
if 'http error: 400, reason: Bad Request' in ex.error_msg:
256-
logger.info('Sniff: not an MSI object id')
255+
except AuthenticationError as ex:
256+
if 'Identity not found' in ex.error_msg:
257+
logger.info('Sniff: not object id')
257258
else:
258259
raise
259260

260261
if not authenticated:
261-
raise CLIError('Failed to connect to MSI, check your managed service identity id.')
262+
raise CLIError('Failed to connect to managed identity, check your managed identity ID.')
262263

263264
else:
264265
identity_type = MsiAccountTypes.system_assigned
265-
msi_creds = MSIAuthenticationWrapper(resource=resource)
266+
cred = ManagedIdentityCredential()
266267

267-
token_entry = msi_creds.token
268-
token = token_entry['access_token']
269-
logger.info('MSI: token was retrieved. Now trying to initialize local accounts...')
268+
token = cred.get_token(*self._arm_scope).token
269+
logger.info('Managed identity: token was retrieved. Now trying to initialize local accounts...')
270270
decode = jwt.decode(token, algorithms=['RS256'], options={"verify_signature": False})
271271
tenant = decode['tid']
272272

273273
subscription_finder = SubscriptionFinder(self.cli_ctx)
274-
subscriptions = subscription_finder.find_using_specific_tenant(tenant, msi_creds)
274+
subscriptions = subscription_finder.find_using_specific_tenant(tenant, cred)
275275
base_name = ('{}-{}'.format(identity_type, identity_id) if identity_id else identity_type)
276276
user = _USER_ASSIGNED_IDENTITY if identity_id else _SYSTEM_ASSIGNED_IDENTITY
277277
if not subscriptions:
278278
if allow_no_subscriptions:
279279
subscriptions = self._build_tenant_level_accounts([tenant])
280280
else:
281-
raise CLIError('No access was configured for the VM, hence no subscriptions were found. '
281+
raise CLIError('No access was configured for the managed identity, hence no subscriptions were found. '
282282
"If this is expected, use '--allow-no-subscriptions' to have tenant level access.")
283283

284284
consolidated = self._normalize_properties(user, subscriptions, is_service_principal=True,

src/azure-cli-core/azure/cli/core/auth/identity.py

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,7 @@
4141

4242

4343
class Identity: # pylint: disable=too-many-instance-attributes
44-
"""Class to manage identities:
45-
- user
46-
- service principal
47-
- TODO: managed identity
48-
"""
44+
"""Manage user and service principal identities."""
4945

5046
# MSAL token cache.
5147
# It follows singleton pattern so that all MSAL app instances share the same token cache.
@@ -200,12 +196,6 @@ def login_with_service_principal(self, client_id, credential, scopes):
200196
entry = sp_auth.get_entry_to_persist()
201197
self._service_principal_store.save_entry(entry)
202198

203-
def login_with_managed_identity(self, scopes, identity_id=None): # pylint: disable=too-many-statements
204-
raise NotImplementedError
205-
206-
def login_in_cloud_shell(self, scopes):
207-
raise NotImplementedError
208-
209199
def logout_user(self, username):
210200
# If username is an SP client ID, it is ignored
211201
accounts = self._msal_app.get_accounts(username)
@@ -252,9 +242,6 @@ def get_service_principal_credential(self, client_id):
252242
client_credential = ServicePrincipalAuth(entry).get_msal_client_credential()
253243
return ServicePrincipalCredential(client_id, client_credential, **self._msal_app_kwargs)
254244

255-
def get_managed_identity_credential(self, client_id=None):
256-
raise NotImplementedError
257-
258245

259246
class ServicePrincipalAuth: # pylint: disable=too-many-instance-attributes
260247
def __init__(self, entry):

src/azure-cli-core/azure/cli/core/auth/msal_credentials.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from knack.log import get_logger
2020
from knack.util import CLIError
2121
from msal import (PublicClientApplication, ConfidentialClientApplication,
22-
ManagedIdentityClient, SystemAssignedManagedIdentity)
22+
ManagedIdentityClient, SystemAssignedManagedIdentity, UserAssignedManagedIdentity)
2323

2424
from .constants import AZURE_CLI_CLIENT_ID
2525
from .util import check_result, build_sdk_access_token
@@ -139,9 +139,14 @@ class ManagedIdentityCredential: # pylint: disable=too-few-public-methods
139139
Currently, only Azure Arc's system-assigned managed identity is supported.
140140
"""
141141

142-
def __init__(self):
142+
def __init__(self, client_id=None, resource_id=None, object_id=None):
143143
import requests
144-
self._msal_client = ManagedIdentityClient(SystemAssignedManagedIdentity(), http_client=requests.Session())
144+
if client_id or resource_id or object_id:
145+
managed_identity = UserAssignedManagedIdentity(client_id=client_id, resource_id=resource_id,
146+
object_id=object_id)
147+
else:
148+
managed_identity = SystemAssignedManagedIdentity()
149+
self._msal_client = ManagedIdentityClient(managed_identity, http_client=requests.Session())
145150

146151
def get_token(self, *scopes, **kwargs):
147152
logger.debug("ManagedIdentityCredential.get_token: scopes=%r, kwargs=%r", scopes, kwargs)

0 commit comments

Comments
 (0)