Skip to content

Commit 3db9bb2

Browse files
skabouckittelmmacy
authored
Initial import of "Device Code flow in Python console app" (#5)
* Create app.py * Create requirements.txt * Update app.py * Create README.md * Update README.md * Update README.md * Update README.md * Update README.md * Apply suggestions from code review Co-authored-by: Chad Kittel <chad.kittel@gmail.com> * Update app.py Updated with formatting from 'black' * Apply suggestions from code review Co-authored-by: Chad Kittel <chad.kittel@gmail.com> * Update README.md "web APP" -> "console" * Update README.md * Update README.md * Update msal-device-flow-python/README.md Co-authored-by: Chad Kittel <chad.kittel@gmail.com> * Apply suggestions from code review Co-authored-by: Marsh Macy <mmacy@users.noreply.github.com> * Update README.md Updated "About the code" Co-authored-by: Chad Kittel <chad.kittel@gmail.com> Co-authored-by: Marsh Macy <mmacy@users.noreply.github.com>
1 parent 2c929a9 commit 3db9bb2

File tree

3 files changed

+178
-0
lines changed

3 files changed

+178
-0
lines changed

msal-device-flow-python/README.md

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
<!-- Keeping yaml frontmatter commented out for now
2+
---
3+
# Metadata required by https://docs.microsoft.com/samples/browse/
4+
# Metadata properties: https://review.docs.microsoft.com/help/contribute/samples/process/onboarding?branch=main#add-metadata-to-readme
5+
languages:
6+
- Python
7+
page_type: sample
8+
name: "Python console application that makes a request to the Graph API via the Device Code flow"
9+
description: "This Python console application uses the device code flow for authentication and then makes a request to Microsoft Graph for the user's profile data."
10+
products:
11+
- azure
12+
- azure-active-directory
13+
- ms-graph
14+
urlFragment: ms-identity-docs-code-app-device-code-python
15+
---
16+
-->
17+
18+
# Python | console | user sign-in, protected web API access (Microsoft Graph) | Microsoft identity platform
19+
20+
<!-- Build badges here
21+
![Build passing.](https://img.shields.io/badge/build-passing-brightgreen.svg) ![Code coverage.](https://img.shields.io/badge/coverage-100%25-brightgreen.svg) ![License.](https://img.shields.io/badge/license-MIT-green.svg)
22+
-->
23+
24+
This Python console application authenticates a user via the device code flow, and then makes a request to the Graph API as the authenticated user. The response to the request is printed to the terminal.
25+
26+
```console
27+
$ python3 app.py
28+
To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code XXXXXXXXX to authenticate.
29+
{
30+
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
31+
"businessPhones": ["+1 (999) 5551001"],
32+
"displayName": "Contoso Employee",
33+
"givenName": "Contoso",
34+
"jobTitle": "Worker",
35+
"mail": "cemployee@contoso.com",
36+
"mobilePhone": "1 999-555-1001",
37+
"officeLocation": "Contoso Plaza/F30",
38+
"preferredLanguage": null,
39+
"surname": "Employee",
40+
"userPrincipalName": "contoso_employee@contoso.com",
41+
"id": "e3a49d8b-d849-48eb-9947-37c1f9589812"
42+
}
43+
```
44+
## Prerequisites
45+
46+
- Azure Active Directory (Azure AD) tenant and the permissions or role required for managing app registrations in the tenant.
47+
- Python 3
48+
49+
## Setup
50+
51+
### 1. Register the app
52+
53+
First, complete the steps in [Register an application with the Microsoft identity platform](https://docs.microsoft.com/azure/active-directory/develop/quickstart-register-app) to register the application.
54+
55+
Use these settings in your app registration.
56+
57+
| App registration <br/> setting | Value for this sample app | Notes |
58+
|---------------------------------:|:-----------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------|
59+
| **Name** | `Python Device Code Flow App` | Suggested value for this sample. <br/> You can change the app name at any time. |
60+
| **Supported account types** | **Accounts in this organizational directory only (Single tenant)** | Suggested value for this sample. |
61+
| **Platform type** | _None_ | No redirect URI required; don't select a platform. |
62+
| **Allow public client flows** | **Yes** | Required value for this sample. |
63+
64+
> :information_source: **Bold text** in the tables above matches (or is similar to) a UI element in the Azure portal, while `code formatting` indicates a value you enter into a text box in the Azure portal.
65+
66+
### 2. Update code sample with app registration values
67+
68+
```python
69+
# Full directory URL, in the form of https://login.microsoftonline.com/<tenant>
70+
"authority": "",
71+
72+
# 'Application (client) ID' of app registration in Azure portal - this value is a GUID
73+
"client_id": ""
74+
```
75+
76+
### 3. Install package(s)
77+
78+
To install MSAL libraries:
79+
80+
```bash
81+
pip install -r requirements.txt
82+
```
83+
84+
## Run the application
85+
86+
```bash
87+
python3 app.py
88+
```
89+
90+
Follow the device code flow instructions that are presented. If everything worked, you should receive a response similar to this:
91+
92+
```json
93+
{
94+
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
95+
"businessPhones": ["+1 (999) 5551001"],
96+
"displayName": "Contoso Employee",
97+
"givenName": "Contoso",
98+
"jobTitle": "Worker",
99+
"mail": "cemployee@contoso.com",
100+
"mobilePhone": "1 999-555-1001",
101+
"officeLocation": "Contoso Plaza/F30",
102+
"preferredLanguage": null,
103+
"surname": "Employee",
104+
"userPrincipalName": "contoso_employee@contoso.com",
105+
"id": "e3a49d8b-d849-48eb-9947-37c1f9589812"
106+
}
107+
```
108+
109+
## About the code
110+
111+
This Python console application prompts the user to sign in via their device using a code provided by Microsoft Authentication Library (MSAL). Upon successful authentication, the 'Requests' library then makes an HTTP GET request to the Microsoft Graph /me endpoint with the user's access token in the HTTP header. The response from the GET request is then displayed to the console.
112+
113+
## Reporting problems
114+
115+
### Sample app not working?
116+
117+
If you can't get the sample working, you've checked [Stack Overflow](http://stackoverflow.com/questions/tagged/msal), and you've already searched the issues in this sample's repository, open an issue report the problem.
118+
119+
1. Search the [GitHub issues](../../issues) in the repository - your problem might already have been reported or have an answer.
120+
1. Nothing similar? [Open an issue](../../issues/new) that clearly explains the problem you're having running the sample app.
121+
122+
### All other issues
123+
124+
> :warning: WARNING: Any issue in this repository _not_ limited to running one of its sample apps will be closed without being addressed.
125+
126+
For all other requests, see [Support and help options for developers | Microsoft identity platform](https://docs.microsoft.com/azure/active-directory/develop/developer-support-help-options).
127+
128+
## Contributing
129+
130+
If you'd like to contribute to this sample, see [CONTRIBUTING.MD](/CONTRIBUTING.md).
131+
132+
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.

msal-device-flow-python/app.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
A Python application that demonstrates how to use the
3+
Device Code flow to make an API call to Microsoft Graph.
4+
"""
5+
6+
# Microsoft Authentication Library (MSAL) for Python
7+
import msal
8+
9+
# Used to allow the app to make the HTTP request to Graph
10+
import requests
11+
12+
# MSAL configs
13+
config = {
14+
# Full directory URL, in the form of https://login.microsoftonline.com/<tenant>
15+
"authority": "",
16+
# 'Application (client) ID' of app registration in Azure portal - this value is a GUID
17+
"client_id": "",
18+
}
19+
20+
# Create a MSAL public client application
21+
msalClientApp = msal.PublicClientApplication(
22+
config["client_id"], authority=config["authority"]
23+
)
24+
25+
# Initialize the Device Code flow for the necessary scope(s)
26+
deviceFlow = msalClientApp.initiate_device_flow(scopes=["User.Read"])
27+
28+
# Displays a message instructing the user to authenticate via their browser
29+
print(deviceFlow["message"], flush=True)
30+
31+
# Get the Graph access token from MSAL
32+
msalResponse = msalClientApp.acquire_token_by_device_flow(deviceFlow)
33+
34+
if "access_token" in msalResponse:
35+
# Make an HTTP GET request to the Graph API using the access token and display the response
36+
print(
37+
requests.get(
38+
"https://graph.microsoft.com/v1.0/me",
39+
headers={"Authorization": "Bearer " + msalResponse["access_token"]},
40+
).json()
41+
)
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Microsoft Authentication Library for Python
2+
msal==1.16.0
3+
4+
# Requests
5+
requests==2.27.1

0 commit comments

Comments
 (0)