---
title: "Authentication"
section: "Libraries: Python"
route: /pythonauth
account: {accountId}
bruce_api: https://{accountId}.api.nextspace.host
guardian_api: https://guardian.nextspace.host
---
# Authentication

Requests are authenticated with a token, which is either a session token from a login or a long-lived access token generated for your account. Both are set the same way and the library sends either as a bearer token, so your code does not need to know which kind it holds.

## Using an access token

An access token needs no login. Hand it to the API instances directly.

```python
import bruce_models as BM

TOKEN = "your-access-token"

guardian = BM.GuardianApi({
    "session_id": TOKEN
})

bruce = BM.BruceApi({
    "account_id": "your-account-id",
    "guardian": guardian,
    "session_id": TOKEN
})
```

## Logging in with credentials

A login returns a session, whose `ID` is the token to use for subsequent requests.

```python
import bruce_models as BM

guardian = BM.GuardianApi()

session = BM.Session.login(
    guardian,
    username="your-username",
    password="your-password",
    account_id="your-account-id"
)
token = session["ID"]

# Apply it to both instances.
guardian.set_session_id(token)
bruce = BM.BruceApi({
    "account_id": "your-account-id",
    "guardian": guardian,
    "session_id": token
})
```

When your user or account enforces multi-factor authentication, supply the code alongside the credentials.

```python
import bruce_models as BM

session = BM.Session.login(
    guardian,
    username="your-username",
    password="your-password",
    account_id="your-account-id",
    # Your MFA/TOTP code.
    code="123456"
)
```

The username can be your user ID, username, or email address. Omitting it entirely means the password is treated as an access token, which is another way to turn a token into a session.

## Ending a session

Logging out invalidates the session attached to the instance. An access token is unaffected, since it is not a session.

```python
import bruce_models as BM

BM.Session.logout(guardian)
```

---

Urls on this page are resolved for account `{accountId}`.
Site index: https://docs.nextspace.host/llms.txt · whole site in one file: https://docs.nextspace.host/llms-full.txt
Human-readable version of this page: https://docs.nextspace.host/pythonauth
