|
| 1 | +--- |
| 2 | +title: Microsoft identity platform Python daemon | Azure |
| 3 | +description: Learn how a Python process can get an access token and call an API protected by Microsoft identity platform endpoint, using the app's own identity |
| 4 | +services: active-directory |
| 5 | +documentationcenter: dev-center-name |
| 6 | +author: jmprieur |
| 7 | +manager: CelesteDG |
| 8 | +editor: '' |
| 9 | + |
| 10 | +ms.assetid: 820acdb7-d316-4c3b-8de9-79df48ba3b06 |
| 11 | +ms.service: active-directory |
| 12 | +ms.subservice: develop |
| 13 | +ms.devlang: na |
| 14 | +ms.topic: quickstart |
| 15 | +ms.tgt_pltfrm: na |
| 16 | +ms.workload: identity |
| 17 | +ms.date: 10/22/2019 |
| 18 | +ms.author: jmprieur |
| 19 | +ms.custom: aaddev, identityplatformtop40 |
| 20 | +#Customer intent: As an application developer, I want to learn how my Python app can get an access token and call an API that's protected by an Microsoft identity platform endpoint using client credentials flow. |
| 21 | +ms.collection: M365-identity-device-management |
| 22 | +--- |
| 23 | + |
| 24 | +# Quickstart: Acquire a token and call Microsoft Graph API from a Python console app using app's identity |
| 25 | + |
| 26 | +In this quickstart, write a Python application that gets an accessing token using the app's identity, and then calls the Microsoft Graph API to display a [list of users](https://docs.microsoft.com/graph/api/user-list) in the directory. This scenario is useful for situations where headless, unattended job or a windows service needs to run with an application identity, instead of a user's identity. |
| 27 | + |
| 28 | +> [!div renderon="docs"] |
| 29 | +>  |
| 30 | +
|
| 31 | +## Prerequisites |
| 32 | + |
| 33 | +To run this sample, you need: |
| 34 | + |
| 35 | +- [Python 2.7+](https://www.python.org/downloads/release/python-2713) or [Python 3+](https://www.python.org/downloads/release/python-364/) |
| 36 | +- [MSAL Python](https://github.com/AzureAD/microsoft-authentication-library-for-python) |
| 37 | + |
| 38 | +> [!div renderon="docs"] |
| 39 | +> ## Register and download your quickstart app |
| 40 | +
|
| 41 | +> [!div renderon="docs" class="sxs-lookup"] |
| 42 | +> |
| 43 | +> You have two options to start your quickstart application: Express (Option 1 below), and Manual (Option 2) |
| 44 | +> |
| 45 | +> ### Option 1: Register and auto configure your app and then download your code sample |
| 46 | +> |
| 47 | +> 1. Go to the new [Azure portal - App registrations](https://portal.azure.com/?Microsoft_AAD_RegisteredApps=true#blade/Microsoft_AAD_RegisteredApps/applicationsListBlade/quickStartType/PythonDaemonQuickstartPage/sourceType/docs) pane. |
| 48 | +> 1. Enter a name for your application and select **Register**. |
| 49 | +> 1. Follow the instructions to download and automatically configure your new application with just one click. |
| 50 | +> |
| 51 | +> ### Option 2: Register and manually configure your application and code sample |
| 52 | +
|
| 53 | +> [!div renderon="docs"] |
| 54 | +> #### Step 1: Register your application |
| 55 | +> To register your application and add the app's registration information to your solution manually, follow these steps: |
| 56 | +> |
| 57 | +> 1. Sign in to the [Azure portal](https://portal.azure.com) using either a work or school account, or a personal Microsoft account. |
| 58 | +> 1. If your account gives you access to more than one tenant, select your account in the top right corner, and set your portal session to the desired Azure AD tenant. |
| 59 | +> 1. Navigate to the Microsoft identity platform for developers [App registrations](https://go.microsoft.com/fwlink/?linkid=2083908) page. |
| 60 | +> 1. Select **New registration**. |
| 61 | +> 1. When the **Register an application** page appears, enter your application's registration information. |
| 62 | +> 1. In the **Name** section, enter a meaningful application name that will be displayed to users of the app, for example `Daemon-console`, then select **Register** to create the application. |
| 63 | +> 1. Once registered, select the **Certificates & secrets** menu. |
| 64 | +> 1. Under **Client secrets**, select **+ New client secret**. Give it a name and select **Add**. Copy the secret on a safe location. You will need it to use in your code. |
| 65 | +> 1. Now, select the **API Permissions** menu, select **+ Add a permission** button, select **Microsoft Graph**. |
| 66 | +> 1. Select **Application permissions**. |
| 67 | +> 1. Under **User** node, select **User.Read.All**, then select **Add permissions** |
| 68 | +
|
| 69 | +> [!div class="sxs-lookup" renderon="portal"] |
| 70 | +> ### Download and configure your quickstart app |
| 71 | +> |
| 72 | +> #### Step 1: Configure your application in Azure portal |
| 73 | +> For the code sample for this quickstart to work, you need to create a client secret, and add Graph API's **User.Read.All** application permission. |
| 74 | +> > [!div renderon="portal" id="makechanges" class="nextstepaction"] |
| 75 | +> > [Make these changes for me]() |
| 76 | +> |
| 77 | +> > [!div id="appconfigured" class="alert alert-info"] |
| 78 | +> >  Your application is configured with these attributes. |
| 79 | +
|
| 80 | +#### Step 2: Download your Python project |
| 81 | + |
| 82 | +[Download the Python daemon project](https://github.com/Azure-Samples/ms-identity-python-daemon/archive/master.zip) |
| 83 | + |
| 84 | +#### Step 3: Configure your Python project |
| 85 | + |
| 86 | +1. Extract the zip file to a local folder close to the root of the disk, for example, **C:\Azure-Samples**. |
| 87 | +1. Navigate to the sub folder **1-Call-MsGraph-WithSecret"**. |
| 88 | +1. Edit **parameters.json** and replace the values of the fields `authority`, `client_id`, and `secret` with the following snippet: |
| 89 | + |
| 90 | + ```json |
| 91 | + "authority": "https://login.microsoftonline.com/Enter_the_Tenant_Id_Here", |
| 92 | + "client_id": "Enter_the_Application_Id_Here", |
| 93 | + "secret": "Enter_the_Client_Secret_Here" |
| 94 | + ``` |
| 95 | + > > [!div renderon="portal" id="certandsecretspage" class="sxs-lookup"] |
| 96 | + > > [Generate a new client secret]() |
| 97 | + |
| 98 | + > [!div class="sxs-lookup" renderon="portal"] |
| 99 | + > > [!NOTE] |
| 100 | + > > This quickstart supports Enter_the_Supported_Account_Info_Here. |
| 101 | + |
| 102 | + > [!div renderon="docs"] |
| 103 | + >> Where: |
| 104 | + >> * `Enter_the_Application_Id_Here` - is the **Application (client) ID** for the application you registered. |
| 105 | + >> * `Enter_the_Tenant_Id_Here` - replace this value with the **Tenant Id** or **Tenant name** (for example, contoso.microsoft.com) |
| 106 | + >> * `Enter_the_Client_Secret_Here` - replace this value with the client secret created on step 1. |
| 107 | + |
| 108 | + > [!div renderon="docs"] |
| 109 | + > > [!TIP] |
| 110 | + > > To find the values of **Application (client) ID**, **Directory (tenant) ID**, go to the app's **Overview** page in the Azure portal. To generate a new key, go to **Certificates & secrets** page. |
| 111 | + |
| 112 | +#### Step 4: Admin consent |
| 113 | + |
| 114 | +If you try to run the application at this point, you'll receive *HTTP 403 - Forbidden* error: `Insufficient privileges to complete the operation`. This error happens because any *app-only permission* requires Admin consent: a global administrator of your directory must give consent to your application. Select one of the options below depending on your role: |
| 115 | + |
| 116 | +##### Global tenant administrator |
| 117 | + |
| 118 | +> [!div renderon="docs"] |
| 119 | +> If you are a global tenant administrator, go to **API Permissions** page in the Azure Portal's Application Registration (Preview) and select **Grant admin consent for {Tenant Name}** (Where {Tenant Name} is the name of your directory). |
| 120 | + |
| 121 | +> [!div renderon="portal" class="sxs-lookup"] |
| 122 | +> If you are a global administrator, go to **API Permissions** page select **Grant admin consent for Enter_the_Tenant_Name_Here** |
| 123 | +> > [!div id="apipermissionspage"] |
| 124 | +> > [Go to the API Permissions page]() |
| 125 | + |
| 126 | +##### Standard user |
| 127 | + |
| 128 | +If you're a standard user of your tenant, then you need to ask a global administrator to grant admin consent for your application. To do this, give the following URL to your administrator: |
| 129 | + |
| 130 | +```url |
| 131 | +https://login.microsoftonline.com/Enter_the_Tenant_Id_Here/adminconsent?client_id=Enter_the_Application_Id_Here |
| 132 | +``` |
| 133 | + |
| 134 | +> [!div renderon="docs"] |
| 135 | +>> Where: |
| 136 | +>> * `Enter_the_Tenant_Id_Here` - replace this value with the **Tenant Id** or **Tenant name** (for example, contoso.microsoft.com) |
| 137 | +>> * `Enter_the_Application_Id_Here` - is the **Application (client) ID** for the application you registered. |
| 138 | +
|
| 139 | +#### Step 5: Run the application |
| 140 | + |
| 141 | +You'll need to install MSAL Python once |
| 142 | + |
| 143 | +```console |
| 144 | +pip install msal |
| 145 | +``` |
| 146 | + |
| 147 | +Then, run the application via command prompt or console: |
| 148 | + |
| 149 | +```console |
| 150 | +python confidential_client_secret_sample.py parameters.json |
| 151 | +``` |
| 152 | + |
| 153 | +You should see on the console output some Json fragment representing a list of users in your Azure AD directory. |
| 154 | + |
| 155 | +> [!IMPORTANT] |
| 156 | +> This quickstart application uses a client secret to identify itself as confidential client. Because the client secret is added as a plain-text to your project files, for security reasons, it is recommended that you use a certificate instead of a client secret before considering the application as production application. For more information on how to use a certificate, see [these instructions](https://github.com/Azure-Samples/ms-identity-python-daemon/blob/master/2-Call-MsGraph-WithCertificate/README.md) in the same GitHub repository for this sample, but in the second folder **2-Call-MsGraph-WithCertificate** |
| 157 | +
|
| 158 | +## More information |
| 159 | + |
| 160 | +### MSAL Python |
| 161 | + |
| 162 | +[MSAL Python](https://github.com/AzureAD/microsoft-authentication-library-for-python) is the library used to sign in users and request tokens used to access an API protected by Microsoft identity platform. As described, this quickstart requests tokens by using the application own identity instead of delegated permissions. The authentication flow used in this case is known as *[client credentials oauth flow](v2-oauth2-client-creds-grant-flow.md)*. For more information on how to use MSAL Python with daemon apps, see [this article](scenario-daemon-overview.md). |
| 163 | + |
| 164 | + You can install MSAL Python by running the following pip command. |
| 165 | + |
| 166 | +```powershell |
| 167 | +pip install -r requirements.txt |
| 168 | +``` |
| 169 | + |
| 170 | +### MSAL initialization |
| 171 | + |
| 172 | +You can add the reference for MSAL by adding the following code: |
| 173 | + |
| 174 | +```Python |
| 175 | +import msal |
| 176 | +``` |
| 177 | + |
| 178 | +Then, initialize MSAL using the following code: |
| 179 | + |
| 180 | +```Python |
| 181 | +app = msal.ConfidentialClientApplication( |
| 182 | + config["client_id"], authority=config["authority"], |
| 183 | + client_credential=config["secret"]) |
| 184 | +``` |
| 185 | + |
| 186 | +> | Where: || |
| 187 | +> |---------|---------| |
| 188 | +> | `config["secret"]` | Is the client secret created for the application in Azure Portal. | |
| 189 | +> | `config["client_id"]` | Is the **Application (client) ID** for the application registered in the Azure portal. You can find this value in the app's **Overview** page in the Azure portal. | |
| 190 | +> | `config["authority"]` | The STS endpoint for user to authenticate. Usually <https://login.microsoftonline.com/{tenant}> for public cloud, where {tenant} is the name of your tenant or your tenant Id.| |
| 191 | +
|
| 192 | +For more information, please see the [reference documentation for `ConfidentialClientApplication`](https://msal-python.readthedocs.io/en/latest/#confidentialclientapplication) |
| 193 | + |
| 194 | +### Requesting tokens |
| 195 | + |
| 196 | +To request a token using app's identity, use `AcquireTokenForClient` method: |
| 197 | + |
| 198 | +```Python |
| 199 | +result = None |
| 200 | +result = app.acquire_token_silent(config["scope"], account=None) |
| 201 | + |
| 202 | +if not result: |
| 203 | + logging.info("No suitable token exists in cache. Let's get a new one from AAD.") |
| 204 | + result = app.acquire_token_for_client(scopes=config["scope"]) |
| 205 | +``` |
| 206 | + |
| 207 | +> |Where:| | |
| 208 | +> |---------|---------| |
| 209 | +> | `config["scope"]` | Contains the scopes requested. For confidential clients, this should use the format similar to `{Application ID URI}/.default` to indicate that the scopes being requested are the ones statically defined in the app object set in the Azure Portal (for Microsoft Graph, `{Application ID URI}` points to `https://graph.microsoft.com`). For custom Web APIs, `{Application ID URI}` is defined under **Expose an API** section in Azure Portal's Application Registration (Preview). | |
| 210 | +
|
| 211 | +For more information, please see the [reference documentation for `AcquireTokenForClient`](https://msal-python.readthedocs.io/en/latest/#msal.ConfidentialClientApplication.acquire_token_for_client) |
| 212 | + |
| 213 | +[!INCLUDE [Help and support](../../../includes/active-directory-develop-help-support-include.md)] |
| 214 | + |
| 215 | +## Next steps |
| 216 | + |
| 217 | +To learn more about daemon applications, see the scenario landing page |
| 218 | + |
| 219 | +> [!div class="nextstepaction"] |
| 220 | +> [Daemon application that calls web APIs](scenario-daemon-overview.md) |
| 221 | +
|
| 222 | +For the daemon application tutorial, see: |
| 223 | + |
| 224 | +> [!div class="nextstepaction"] |
| 225 | +> [Daemon Python console tutorial](https://github.com/Azure-Samples/ms-identity-python-daemon) |
| 226 | +
|
| 227 | +Learn more about permissions and consent: |
| 228 | + |
| 229 | +> [!div class="nextstepaction"] |
| 230 | +> [Permissions and Consent](v2-permissions-and-consent.md) |
| 231 | +
|
| 232 | +To know more about the auth flow for this scenario, see the Oauth 2.0 client credentials flow: |
| 233 | + |
| 234 | +> [!div class="nextstepaction"] |
| 235 | +> [Client credentials Oauth flow](v2-oauth2-client-creds-grant-flow.md) |
| 236 | +
|
| 237 | +Help us improve the Microsoft identity platform. Tell us what you think by completing a short two-question survey. |
| 238 | + |
| 239 | +> [!div class="nextstepaction"] |
| 240 | +> [Microsoft identity platform survey](https://forms.office.com/Pages/ResponsePage.aspx?id=v4j5cvGGr0GRqy180BHbRyKrNDMV_xBIiPGgSvnbQZdUQjFIUUFGUE1SMEVFTkdaVU5YT0EyOEtJVi4u) |
0 commit comments