# Manage service accounts and tokens
> Use the MotherDuck UI and REST API to view, delete, and rotate service account tokens.
Use the MotherDuck UI for service account inventory and one-off administration. Use the REST API when your automation already knows the target service account username.

:::warning[Service account permissions required]
Viewing or managing service accounts and their tokens in the MotherDuck UI requires the corresponding permission for each action. The Admin and Builder preset roles include these permissions by default. The Admin REST API examples require a read/write access token generated by an Admin user.
:::

:::note
Before querying a database or share with a Read Scaling token, attach the databases the account needs using a read/write token or [impersonation](/key-tasks/service-accounts-guide/impersonate-service-accounts/).
:::

## Check what each interface supports

| Task | MotherDuck UI | REST API |
|---|---|---|
| List all users and service accounts in an organization | Yes | Yes, with [`GET /v1/users`](/sql-reference/rest-api/motherduck-rest-api/) |
| Create a service account | Yes | Yes, with [`POST /v1/users`](/sql-reference/rest-api/users-create-service-account/) |
| View tokens for a known service account | Yes | Yes, with [`GET /v1/users/{username}/tokens`](/sql-reference/rest-api/users-list-tokens/) |
| Create a token for a known service account | Yes | Yes, with [`POST /v1/users/{username}/tokens`](/sql-reference/rest-api/users-create-token/) |
| Revoke a known token | Yes | Yes, with [`DELETE /v1/users/{username}/tokens/{token_id}`](/sql-reference/rest-api/users-delete-token/) |
| Delete a known service account | Yes | Yes, with [`DELETE /v1/users/{username}`](/sql-reference/rest-api/users-delete/) |
| View or configure Ducklings for a known service account | Yes | Yes, with the [Duckling configuration endpoints](/sql-reference/rest-api/ducklings-get-duckling-config-for-user/) |
| Impersonate a service account | Yes | No |

`GET /v1/users` returns every user and service account in the caller's organization, with each account's roles, so your automation no longer has to keep its own record of the usernames it provisioned.

## View service accounts

### UI

![Service account management page](../img/sa_manage_details.png)

1. In the MotherDuck UI, go to **Settings** > **Service Accounts**.
2. Review the service account list.
3. Click a username to open a panel with that service account's access tokens.
4. Use the Duckling size and pool size dropdowns to review compute configuration.

### API

Use `GET /v1/users` to list every user and service account in your organization, ordered by username. Any user who can view the organization's members can call it, which by default is every [role](/concepts/security-and-access/roles-and-access-control/): Admin, Builder, and Explorer.

```bash
curl -G \
  https://api.motherduck.com/v1/users \
  -H "Authorization: Bearer <token>" \
  -d "is_service_account=true"
```

The response contains a `users` array, the `total_count` of accounts that match your filters, and a `next_page_token`:

```json
{
  "users": [
    {
      "id": "3f2b1c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
      "username": "analytics_service_account",
      "email": "sa-3f2b1c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d@sa.motherduck.com",
      "first_name": "service",
      "last_name": "account",
      "is_service_account": true,
      "is_deprovisioned": false,
      "roles": ["builder"]
    }
  ],
  "total_count": 1,
  "next_page_token": null
}
```

- `roles` lists the names of the roles assigned directly to each account, such as `admin`, `builder`, `explorer`, or a custom role. It doesn't include roles inherited through a custom role.
- Service accounts get a system-generated `email` and the placeholder name "service account". Use `is_service_account`, not the email or name, to tell them apart from human users.

### Filter the list

| Parameter | Description |
|---|---|
| `is_service_account` | `true` returns only service accounts; `false` returns only human users. |
| `is_deprovisioned` | `true` returns only deprovisioned accounts; `false` excludes them. |
| `limit` | Accounts per page, up to 1000. Defaults to 1000. |
| `page_token` | The `next_page_token` from the previous response, to fetch the next page. |
| `offset` | Number of accounts to skip. `page_token` takes precedence when you send both. |

### Page through large organizations

Each response includes a `next_page_token`. Pass it as `page_token` to fetch the next page, and stop when `next_page_token` is `null`. An invalid `page_token` returns a `400` error.

```bash
TOKEN=""
while :; do
  PAGE=$(curl -sG https://api.motherduck.com/v1/users \
    -H "Authorization: Bearer <token>" \
    -d "limit=500" ${TOKEN:+-d "page_token=$TOKEN"})
  echo "$PAGE" | jq -r '.users[].username'
  TOKEN=$(echo "$PAGE" | jq -r '.next_page_token // empty')
  [ -z "$TOKEN" ] && break
done
```

## View tokens for a service account

The token list shows token metadata, including token ID, name, type, creation time, and expiration time. It doesn't return the token secret.

### UI

1. In **Settings** > **Service Accounts**, click the service account's username to open its details panel.
2. Review the token list.

### API using curl

Use [`GET /v1/users/{username}/tokens`](/sql-reference/rest-api/users-list-tokens/) to list tokens for a known service account username.

```bash
curl -X GET \
  https://api.motherduck.com/v1/users/analytics_service_account/tokens \
  -H "Authorization: Bearer <admin_token>"
```

### API using Python

Use [`GET /v1/users/{username}/tokens`](/sql-reference/rest-api/users-list-tokens/) to list tokens for a known service account username.

```python
import pprint
import requests

response = requests.get(
    "https://api.motherduck.com/v1/users/analytics_service_account/tokens",
    headers={"Authorization": "Bearer <admin_token>"},
)

response.raise_for_status()
pprint.pp(response.json()["tokens"])
```

## Change a service account's role

A new service account gets the Explorer [role](/concepts/security-and-access/roles-and-access-control/). To give it more platform permissions or data access, assign another role with [`GRANT ROLE`](/sql-reference/motherduck-sql-reference/access-control/grant-role/), and remove one with [`REVOKE ROLE`](/sql-reference/motherduck-sql-reference/access-control/revoke-role/):

```sql
GRANT ROLE builder TO USER analytics_service_account;
REVOKE ROLE builder FROM USER analytics_service_account;
```

You don't need to create new tokens after a role change. A token identifies the service account, not a set of permissions: MotherDuck looks up the account's current roles when the token authenticates, so every existing token, and every connection already open with one, picks up the change.

- **Granting a role** takes effect on the account's next request.
- **Revoking a role** can take up to 10 minutes to reach tokens that are already in use, because MotherDuck caches each token's roles.
- **`session_roles()` and `is_role_in_session()`** can take up to a minute to reflect a change in a connection that is already open.

To cut off a workload's access faster than a role revoke, [revoke its tokens](#revoke-a-token) and restart the workload.

## Check a service account's roles

Connect with the service account's token and run [`session_roles()`](/key-tasks/sharing-data/secure-views/#show-each-consumer-different-rows) to see the roles that connection holds, including the preset roles it inherits. Calling `session_roles()` directly requires DuckDB 1.5.6 or later; older clients return `Scalar Function with name session_roles does not exist`.

```sql
SELECT current_user(), session_roles();
```

```text
┌───────────────────────────┬─────────────────┐
│      current_user()       │ session_roles() │
├───────────────────────────┼─────────────────┤
│ analytics_service_account │ [explorer]      │
└───────────────────────────┴─────────────────┘
```

MotherDuck has no `current_role()` function, because a session holds a set of roles rather than one current role. To see which roles are assigned directly and which are inherited, use [`SHOW ROLES TO USER`](/sql-reference/motherduck-sql-reference/access-control/show-roles/#show-roles-to-user). An account can always run it for its own username:

```sql
SHOW ROLES TO USER analytics_service_account;
```

Over the REST API, [`GET /v1/users`](#view-service-accounts) returns each account's directly assigned roles in its `roles` field. The REST API has no endpoint that returns the caller's own identity, so look up the service account by username.

## Rotate a service account token

Rotate tokens by creating a replacement token before revoking the old token.

1. Create a replacement token for the service account.
2. Update your secret manager or application configuration to use the replacement token.
3. Deploy or restart clients that use the token.
4. Verify that the workload can connect to MotherDuck with the replacement token.
5. Revoke the old token.

## Revoke a token

A revoked token can't open new connections: a client that starts with it fails with `PERMISSION_DENIED, RPC 'CREATE_SLT'`. Connections that are already open, and new connections from a process that already connected with the token, can keep working for 10 minutes or more. Restart the clients that used the token to end those sessions.

### UI

![Service account token actions](../img/sa_revoke_token_option.png)

1. In **Settings** > **Service Accounts**, click the service account's username to open its details panel.
2. Open the token's three-dot menu.
3. Click **Revoke token**.
4. Confirm the revocation.

### API using curl

Use [`DELETE /v1/users/{username}/tokens/{token_id}`](/sql-reference/rest-api/users-delete-token/) to revoke a known token.

```bash
curl -X DELETE \
  "https://api.motherduck.com/v1/users/analytics_service_account/tokens/<token_id>" \
  -H "Authorization: Bearer <admin_token>"
```

### API using Python

Use [`DELETE /v1/users/{username}/tokens/{token_id}`](/sql-reference/rest-api/users-delete-token/) to revoke a known token.

```python
import requests

response = requests.delete(
    "https://api.motherduck.com/v1/users/analytics_service_account/tokens/<token_id>",
    headers={"Authorization": "Bearer <admin_token>"},
)

response.raise_for_status()
```

## Delete a service account

Deleting a service account immediately revokes its tokens and permanently deletes data owned by that account.

:::warning[This action can't be undone]
Verify the service account username before deleting it. Data and users deleted through the API can't be recovered.
:::

### UI

1. In **Settings** > **Service Accounts**, find the service account.
2. Open the service account's three-dot menu.
3. Click **Delete account**.
4. Confirm the deletion.

### API using curl

Use [`DELETE /v1/users/{username}`](/sql-reference/rest-api/users-delete/) to delete a known service account.

```bash
curl -X DELETE \
  https://api.motherduck.com/v1/users/analytics_service_account \
  -H "Authorization: Bearer <admin_token>"
```

### API using Python

Use [`DELETE /v1/users/{username}`](/sql-reference/rest-api/users-delete/) to delete a known service account.

```python
import requests

response = requests.delete(
    "https://api.motherduck.com/v1/users/analytics_service_account",
    headers={"Authorization": "Bearer <admin_token>"},
)

response.raise_for_status()
print(response.json()["username"])
```

## Related content

- [Create and configure service accounts](/key-tasks/service-accounts-guide/create-and-configure-service-accounts/)
- [Impersonate service accounts](/key-tasks/service-accounts-guide/impersonate-service-accounts/)
- [MotherDuck REST API](/sql-reference/rest-api/motherduck-rest-api/)


---

## Docs feedback

MotherDuck accepts optional user-submitted feedback about this page at `GET https://motherduck.com/docs/api/feedback/agent`.
For agents and automated tools, feedback submission should be user-confirmed before sending.

URL-encode query parameter values and send a GET request:

```text
GET https://motherduck.com/docs/api/feedback/agent?page_path=%2Fkey-tasks%2Fservice-accounts-guide%2Fmanage-service-accounts-and-tokens%2F&page_title=Manage%20service%20accounts%20and%20tokens&text=<url-encoded user feedback, max 2000 characters>
```

Optionally append `&source=<url-encoded interface identifier>` such as `claude.ai` or `chatgpt`.

`page_path` and `text` are required; `page_title` and `source` are optional. Responses: `200 {"feedback_id": "<uuid>"}`, `400` for malformed query parameters, and `429` when rate-limited.
