# Authenticate a Python script with OAuth credentials

> Use a client ID and secret from a backend Python script. requests-oauthlib gets the app token and adds it to every request to the REST API.

Interactive version: http://www.rauljimenez.info/arcgis-tutorials/python-app-auth/

## What you will build

A Python script, `app_auth.py`, that authenticates as an application, without a user, with OAuth 2.0 credentials and the client credentials flow:

* It exchanges a client ID and client secret for an app token using [requests-oauthlib](https://requests-oauthlib.readthedocs.io/en/latest/).
* It calls the [portals/self](https://developers.arcgis.com/rest/users-groups-and-items/portal-self/) endpoint with that token and prints the privileges the token carries.

You will create the OAuth credentials in the portal first, then write the script that uses them.

<details>
<summary>Check prerequisites</summary>
<p>You will need an ArcGIS Location Platform, ArcGIS Online, or ArcGIS Enterprise account that can create developer credentials. In ArcGIS Online and ArcGIS Enterprise, that means a user type of Creator or higher.</p>
<p>To run the script: Python 3.12 or later and <code>requests-oauthlib</code> (<code>pip install requests-oauthlib</code>), which installs <code>oauthlib</code> too.</p>
</details>

*Adapted from an original tutorial by [Dave Olsthoorn](https://www.linkedin.com/in/dave-olsthoorn/).*

## Create the OAuth credentials

Create the credentials for your script in [your portal](https://developers.arcgis.com/documentation/glossary/arcgis-portal/):

1. Go to **Content** > **My content** > **New item**.
2. Click **Developer credentials**.
3. Select **OAuth 2.0 credentials (_For app authentication_)**.
4. Select **Private application with selected privileges**, so the token gets only the privileges you grant.
5. Select **No item access**. This script reads no items; for your own app, grant access only to the items it needs.
6. Leave the privileges off. This script needs none; for your own app, enable only the ones it calls.
7. Leave the referrer URLs empty. A backend script doesn't need them: they help only when the token ends up in a web browser.
8. Fill in the item details.
9. Review the summary and create the item.
10. Copy the **Client ID** and the **Client Secret**.

![1-create-new-item.png](http://www.rauljimenez.info/arcgis-tutorials/_astro/1-create-new-item.B7uQ9Jdo.png)

![2-select-developer-credentials.png](http://www.rauljimenez.info/arcgis-tutorials/_astro/2-select-developer-credentials.Dk5dvPuI.png)

![3-select-oauth2-app-auth.png](http://www.rauljimenez.info/arcgis-tutorials/_astro/3-select-oauth2-app-auth.CJdmm5Gb.png)

![4-select-private-app-privileges.png](http://www.rauljimenez.info/arcgis-tutorials/_astro/4-select-private-app-privileges.C07SPufL.png)

![5-select-no-item-access.png](http://www.rauljimenez.info/arcgis-tutorials/_astro/5-select-no-item-access.CL7M0qVr.png)

![6-no-extra-privileges.png](http://www.rauljimenez.info/arcgis-tutorials/_astro/6-no-extra-privileges.CuvnN7D6.png)

![7-no-referrer.png](http://www.rauljimenez.info/arcgis-tutorials/_astro/7-no-referrer.Ha1Cxjvw.png)

![8-item-details.png](http://www.rauljimenez.info/arcgis-tutorials/_astro/8-item-details.UaBT4egU.png)

![9-item-review.png](http://www.rauljimenez.info/arcgis-tutorials/_astro/9-item-review.pYlSDUU0.png)

![10-credentials.png](http://www.rauljimenez.info/arcgis-tutorials/_astro/10-credentials.QvKXwKdM.png)

## Import the library

Import two classes:

- `BackendApplicationClient`, from oauthlib, tells the session to use the client credentials flow, for a backend client with no user. It also stores the client ID.
- `OAuth2Session`, from requests-oauthlib, is a `requests` session that gets the token and adds it to every request you send with it.

```python title="code/app_auth.py" region="library"
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
```

## Configure the script

Paste the client ID and the client secret from the credentials item:

- **Set your Client ID:** (`client_id`)
- **Set your Client Secret:** (`client_secret`)

> **The client secret is as sensitive as a password.** Keep it in server-side code only, and out of your repository: in production, read it from the environment or a secret manager.

<details>
<summary>Authenticating against ArcGIS Enterprise?</summary>

If you created the credentials in ArcGIS Enterprise, set the Portal URL:

- **Portal URL** (`portal_url`)

</details>

```python title="code/app_auth.py" region="config"
client_id = "<client_id>"
client_secret = "<client_secret>"
portal_url = "https://www.arcgis.com"
```

## Build the token endpoint

The script requests its token from the portal's OAuth 2.0 token endpoint: the portal URL followed by `/sharing/rest/oauth2/token`.

```python title="code/app_auth.py" region="token-endpoint"
# Token URL endpoint for oauth2
token_url = f"{portal_url}/sharing/rest/oauth2/token"
```

## Set up the OAuth session

Create the client with your client ID, and the session from the client. The session uses it to request the token and to send your requests with it.

`auto_refresh_url` and `auto_refresh_kwargs` let the `OAuth2Session` request new tokens with the refresh token instead of the client secret.

```python title="code/app_auth.py" region="oauth"
# Create client & session with client_id
client = BackendApplicationClient(client_id=client_id)
session = OAuth2Session(
    client=client,
    auto_refresh_url=token_url,
    auto_refresh_kwargs={"client_id": client_id},
)
```

## Request a token

Call `fetch_token` with the client secret. The ArcGIS REST API expects the client ID and the client secret as parameters of the POST request, so set `include_client_id=True`.

The session stores the token in its `token` attribute.

```python title="code/app_auth.py" region="token"
# Actually fetch the token
session.fetch_token(
    token_url=token_url,
    client_secret=client_secret,
    include_client_id=True
)
```

## Make a request

Send requests to the ArcGIS REST API or to ArcGIS services through the session: it adds the token to each one in the `Authorization` header. The script uses `get()`, and the other `requests` methods, such as `post()`, work the same way.

The script calls [portals/self](https://developers.arcgis.com/rest/users-groups-and-items/portal-self/), which returns the application's title and the privileges of its token, among other details.

```python title="code/app_auth.py" region="request"
# Make a request using the token
response = session.get(
    f"{portal_url}/sharing/rest/portals/self",
    params={"f": "json"},
)

response.raise_for_status()

portal_info = response.json()
print(f"Title: \"{portal_info["appinfo"]["appTitle"]}\"")
print("Has the following privileges:")
for privilege in portal_info["appinfo"]["privileges"]:
    print(f"\t- {privilege}")
```

## Run the script

Run the script. It prints the title of the credentials item and the privileges of the token:

```
> python app_auth.py
Title: "Tutorial: App Authentication with python requests-oauthlib"
Has the following privileges:
    - premium:user:basemaps
```

Your script authenticates as an application. To act on behalf of your users instead, [sign them in with OAuth 2.0 in a browser app](../arcgis-js-sdk-user-auth/).

## Final code

### code/app_auth.py

```python title="code/app_auth.py"
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session

client_id = "<client_id>"
client_secret = "<client_secret>"
portal_url = "https://www.arcgis.com"

# Token URL endpoint for oauth2
token_url = f"{portal_url}/sharing/rest/oauth2/token"

# Create client & session with client_id
client = BackendApplicationClient(client_id=client_id)
session = OAuth2Session(
    client=client,
    auto_refresh_url=token_url,
    auto_refresh_kwargs={"client_id": client_id},
)

# Actually fetch the token
session.fetch_token(
    token_url=token_url,
    client_secret=client_secret,
    include_client_id=True
)

# Make a request using the token
response = session.get(
    f"{portal_url}/sharing/rest/portals/self",
    params={"f": "json"},
)

response.raise_for_status()

portal_info = response.json()
print(f"Title: \"{portal_info["appinfo"]["appTitle"]}\"")
print("Has the following privileges:")
for privilege in portal_info["appinfo"]["privileges"]:
    print(f"\t- {privilege}")
```
