services | platforms | author | level | client | service | endpoint |
---|---|---|---|---|---|---|
active-directory |
python |
abpati |
200 |
Python Web App |
Microsoft Graph |
AAD v1.0 |
This sample demonstrates how to build a Python (Flask) web application that authorizes Azure Active Directory users and access data from the Microsoft Graph.
- The app uses the Active Directory Authentication Library (ADAL) to acquire a JWT access token for the Microsoft Graph.
- The app then uses the access token to get data about the user from the Microsoft Graph.
To run this sample, you'll need:
- Python 2.7+ or Python 3+
- Flask
- ADAL Python
- An Azure AD tenant
- An Azure AD user. Note: this sample does not support Microsoft accounts.
From your shell or command line:
git clone https://github.com/Azure-Samples/active-directory-python-webapp-graphapi.git
To avoid file name length limitations in Windows, clone the repo close to your root directory.
There is one project in this sample. To register it, you can:
- either follow the steps Step 2: Register the sample with your Azure Active Directory tenant and Step 3: Configure the sample to use your Azure AD tenant
- or use PowerShell scripts that:
- automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you
- modify the configuration file of your project.
If you want to use this automation:
- On Windows run PowerShell and navigate to the root of the cloned directory
- In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
- Run the script to create your Azure AD application and configure the code of the sample application accordingly.
.\AppCreationScripts\Configure.ps1
Other ways of running the scripts are described in App Creation Scripts
As a first step you'll need to:
- Sign in to the Azure portal using either a work or school account or a personal Microsoft account.
- If your account is present in more than one Azure AD tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory. Change your portal session to the desired Azure AD tenant.
- Navigate to the Microsoft identity platform for developers App registrations page.
- Select New registration.
- When the Register an application page appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
PythonWebApp
. - Leave Supported account types on the default setting of Accounts in this organizational directory only.
- In the Redirect URI (optional) section, select Web in the combo-box and enter the following redirect URIs:
http://localhost:5000/getAToken
.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- Select Register to create the application.
- On the app Overview page, find the Application (client) ID value and record it for later. You'll need it to configure the Visual Studio configuration file for this project.
-
Select Save.
-
From the Certificates & secrets page, in the Client secrets section, choose New client secret:
- Type a key description (of instance
app secret
), - Select a key duration of either In 1 year, In 2 years, or Never Expires.
- When you press the Add button, the key value will be displayed, copy, and save the value in a safe location.
- You'll need this key later to configure the project in Visual Studio. This key value will not be displayed again, nor retrievable by any other means, so record it as soon as it is visible from the Azure portal.
- Type a key description (of instance
-
Select the API permissions section
- Click the Add a permission button and then,
- Ensure that the Microsoft APIs tab is selected
- In the Commonly used Microsoft APIs section, click on Microsoft Graph
- In the Delegated permissions section, ensure that the right permissions are checked: User.Read. Use the search box if necessary.
- Select the Add permissions button
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
Open the config.py file to configure the project
Note: if you used the setup scripts, the changes below will have been applied for you
- Open the
config.py
file - Find the app key
TENANT
and replace the existing value with your Azure AD tenant name. - Find the app key
CLIENT_SECRET
and replace the existing value with the key you saved during the creation of thePythonWebApp
app, in the Azure portal. - Find the app key
CLIENT_ID
and replace the existing value with the application ID (clientId) of thePythonWebApp
application copied from the Azure portal.
-
You will need to install Flask framework and the ADAL Python library using pip as follows:
$ pip install flask $ pip install adal
-
If the environment variable for Flask is already set:
Run app.py from shell or command line:
$ python app.py
-
If the environment variable for Flask is not set:
Type the following commands on shell or command line by navigating to the project directory:
$ export FLASK_APP=app.py $ export FLASK_DEBUG=1 $ flask run
Follow the sign-in process to complete the logging.
The code acquiring a token is located in app.py
file.
The sample first starts sign in by redirecting the application from @app.route("/")
to @app.route("/login")
. It forms an authorization url that goes to the Authorization endpoint here:
authorization_url = TEMPLATE_AUTHZ_URL.format(
config.TENANT,
config.CLIENT_ID,
REDIRECT_URI,
auth_state,
config.RESOURCE)
resp = Response(status=307)
resp.headers['location']= authorization_url
return resp
After the user logs in, the authorization code is used acquire a token in @app.route("/getAToken")
.
The AuthenticationContext
is created here:
auth_context = AuthenticationContext(AUTHORITY_URL, api_version=None)
The acquire_token_with_authorization_code() function requests for an access token using the authorization code here:
token_response = auth_context.acquire_token_with_authorization_code(code,REDIRECT_URI,config.RESOURCE, config.CLIENT_ID, config.CLIENT_SECRET)
This token is then used to call the Graph API in @app.route("/graphcall")
:
graph_data = SESSION.get(endpoint,headers = http_headers, stream=False).json()
This project has one WebApp / Web API projects. To deploy them to Azure Web Sites, you'll need, for each one, to:
- create an Azure Web Site
- publish the Web App / Web APIs to the web site, and
- update its client(s) to call the web site instead of IIS Express.
- Sign in to the Azure portal.
- Click
Create a resource
in the top left-hand corner, select Web --> Web App, and give your web site a name, for example,PythonWebApp-contoso.azurewebsites.net
. - Thereafter select the
Subscription
,Resource Group
,App service plan and Location
.OS
will be Windows andPublish
will be Code. - Click
Create
and wait for the App Service to be created. - Once you get the
Deployment succeeded
notification, then click onGo to resource
to navigate to the newly created App service. - Once the web site is created, locate in the Dashboard and click it to open App Services Overview screen.
- Navigate back to to the Azure portal. In the left-hand navigation pane, select the Azure Active Directory service, and then select App registrations.
- In the resultant screen, select the
PythonWebApp
application. - From the Branding menu, update the Home page URL, to the address of your service, for example https://PythonWebApp-contoso.azurewebsites.net. Save the configuration.
- Add the same URL in the list of values of the Authentication -> Redirect URIs menu. If you have multiple redirect urls, make sure that there a new entry using the App service's Uri for each redirect url.
Use Stack Overflow to get support from the community.
Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
Make sure that your questions or comments are tagged with [adal
python
].
If you find a bug in the sample, please raise the issue on GitHub Issues.
To provide a recommendation, visit the following User Voice page.
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.
For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.