2

I'd like to ask Azure for the details of the currently signed in user programmatically within a Python program. The program might run from the command line or within Azure batch.

Is there way to do the same thing as the azure cli does with az ad signed-in-user show, but through the Azure SDK for Python?

UPDATE:

Based on Gaurav's help and pointer to the Microsoft Graph Python Client Library, I tried the following:

from azure.identity import DefaultAzureCredential
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
from msgraphcore import GraphSession

credential = DefaultAzureCredential(
    exclude_shared_token_cache_credential=True,
)

account_name = "mydatalake"
container_name = "test"

service = BlobServiceClient(
    account_url=f"https://{account_name}.blob.core.windows.net/",
    credential=credential
)

container_client = service.get_container_client(container_name)
blob_list = container_client.list_blobs()
for i, blob in enumerate(blob_list):
    print("\t" + blob.name)
    if i >= 9: break

scopes = ['user.read']
graph_session = GraphSession(credential, scopes)
result = graph_session.get('/me')
print(result.json())

I successfully get back blob names from a storage account. But it fails when it gets to the GraphAPI part with this stack trace:

Traceback (most recent call last):
  File "py/src/azure_whoami.py", line 58, in <module>
    result = graph_session.get('/me')
  File "[...snip...]/site-packages/msgraphcore/middleware/options/middleware_control.py", line 24, in wrapper
    return func(*args, **kwargs)
  File "[...snip...]/site-packages/msgraphcore/graph_session.py", line 41, in get
    return super().get(self._graph_url(url))
  File "[...snip...]/site-packages/requests/sessions.py", line 555, in get
    return self.request('GET', url, **kwargs)
  File "[...snip...]/site-packages/requests/sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "[...snip...]/site-packages/requests/sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "[...snip...]/site-packages/msgraphcore/middleware/middleware.py", line 26,
in send
    return self._middleware.send(request, **kwargs)
  File "[...snip...]/site-packages/msgraphcore/middleware/authorization.py", line 16, in send
    request.headers.update({'Authorization': 'Bearer {}'.format(self._get_access_token())})
  File "[...snip...]/site-packages/msgraphcore/middleware/authorization.py", line 33, in _get_access_token
    return self.credential.get_token(*self.scopes)[0]
  File "[...snip...]/site-packages/azure/identity/_credentials/default.py", line 138, in get_token
    token = self._successful_credential.get_token(*scopes, **kwargs)
  File "[...snip...]/site-packages/azure/identity/_internal/decorators.py", line 27, in wrapper
    token = fn(*args, **kwargs)
  File "[...snip...]/site-packages/azure/identity/_credentials/azure_cli.py", line
58, in get_token
    raise error
azure.identity._exceptions.CredentialUnavailableError: Please run 'az login' to set up an account
cbare
  • 12,060
  • 8
  • 56
  • 63

1 Answers1

1

Based on the instructions provided here, you would first need to install the appropriate SDKs (msgraphcore and azure-identity).

After that your code would be something like (again taking from the same link)

# import modules
from azure.identity import UsernamePasswordCredential, DeviceCodeCredential
from msgraphcore import GraphSession

# Configuring credentials
# Added UsernamePassword for demo purposes only, please don't use this in production.
# ugly_credential = UsernamePasswordCredential('set-clientId', 'set-username', 'set-password')

device_credential = DeviceCodeCredential(
    'set-clientId')

# There are many other options for getting an access token. See the following for more information.
# https://pypi.org/project/azure-identity/

# get data
scopes = ['user.read']
graph_session = GraphSession(device_credential, scopes)
result = graph_session.get('/me')
print(result.json())
Gaurav Mantri
  • 128,066
  • 12
  • 206
  • 241
  • Thanks, this looks like exactly what I want. They've left the hard part as an exercise for the reader. I haven't managed to get a credential that can successfully open a GraphSession. I thought I could use `credential = DefaultAzureCredential()`, but that seems not to work. – cbare Apr 20 '21 at 00:41
  • I saw a question yesterday about credentials not working: https://stackoverflow.com/questions/67165101/azure-chainedtokencredential-fails-after-password-change. Please see if this is the case for you as well. HTH. – Gaurav Mantri Apr 20 '21 at 00:57
  • Where do I get a clientId that will work with DeviceCodeCredentials? – cbare Apr 20 '21 at 01:50
  • If you have created an application in Azure AD, the client id is the application id of that application. Go to Azure Active Directory in Azure Portal --> App Registrations --> Find your application --> You can see the id in overview tab. – Gaurav Mantri Apr 20 '21 at 02:17