forked from Neoteroi/BlackSheep-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_using_secret.py
62 lines (50 loc) · 1.82 KB
/
client_using_secret.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""
This module shows an example of how the client credentials flow with secret can be
used with Azure Active Directory and MSAL for Python.
"""
import asyncio
import logging
import os
import httpx
import msal
from dotenv import load_dotenv
# read .env file into environment variables
load_dotenv()
logging.basicConfig(level=logging.DEBUG)
logging.getLogger("msal").setLevel(logging.INFO)
app = msal.ConfidentialClientApplication(
os.environ["APP_CLIENT_ID"],
authority=os.environ["AAD_AUTHORITY"],
client_credential=os.environ["APP_CLIENT_SECRET"],
)
scope = [os.environ["APP_CLIENT_SCOPE"]]
result = app.acquire_token_silent(scope, account=None)
if not result:
logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
result = app.acquire_token_for_client(scopes=scope)
if "access_token" in result:
access_token = result["access_token"]
logging.info("Access token %s", access_token)
async def calls():
# call the API using the access token
async with httpx.AsyncClient(timeout=60) as client:
for _ in range(4):
response = await client.get(
"http://localhost:5000",
headers={"Authorization": f"Bearer {access_token}"},
)
if response.status_code != 200:
logging.error(
"The request to the API failed, with status %s",
response.status_code,
)
else:
logging.info(
"The request to the API server succeeded. Response body: %s",
response.text,
)
asyncio.run(calls())
else:
print(result.get("error"))
print(result.get("error_description"))
print(result.get("correlation_id"))