> For the complete documentation index, see [llms.txt](https://docs.prestd.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.prestd.com/api-reference/auth.md).

# Auth

***prestd*** has support in **JWT Token** generation based on two fields (example user and password), being possible to use an existing table from your database to login configuring some parameters in the configuration file (or environment variable), *by default this feature is* **disabled**.

* Bearer - [RFC 6750](https://tools.ietf.org/html/rfc6750), bearer tokens to access OAuth 2.0-protected resources
* Basic - [RFC 7617](https://tools.ietf.org/html/rfc7617), base64-encoded credentials. More information below

> understand more about *http authentication* [see this documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication)

***

## JWT verification (v2 defaults)

JWT middleware is **disabled by default** in v2+ (`jwt.default = false`). Set `jwt.default = true` to require a valid Bearer token on all endpoints except those in the JWT whitelist. See [Configuring pREST — JWT](https://docs.prestd.com/get-started/configuring-prest.md#jwt) for full configuration.

MCP (`/_mcp`, v2.1.0+) inherits the same JWT and auth stack as REST routes. When auth is enabled, send credentials on every `GET` and `POST` to `/_mcp`. Stdio clients that use the [pREST MCP Adapter](https://docs.prestd.com/get-started/prest-mcp-adapter.md) can pass a bearer token via `PREST_MCP_TOKEN`.

### Routes that require auth (v2.5.2)

With `auth.enabled = true`, every route except `/auth`, `/_health`, `/_ready`, and `/_studio` requires a bearer token. Before v2.5.2 the catalog routes and `/_PLUGIN` answered without one ([GHSA-fhf5-m388-4w4p](https://github.com/prest/prest/security/advisories/GHSA-fhf5-m388-4w4p), [GHSA-fmr6-9j48-xrqp](https://github.com/prest/prest/security/advisories/GHSA-fmr6-9j48-xrqp)).

The table below lists the route stacks that `auth.enabled = true` installs. It does not describe `jwt.default`: with `jwt.default = true`, the JWT middleware wraps every route, including `/_health` and `/_ready`. See [Health and readiness probes](#health-and-readiness-probes).

| Route                                                                                            | With `auth.enabled = true`                                        |
| ------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- |
| `/{database}/{schema}/{table}`, `/batch/{database}/{schema}/{table}`                             | Token + table ACL                                                 |
| `/databases`, `/schemas`, `/tables`, `/{database}/{schema}`, `/show/{database}/{schema}/{table}` | Token + table ACL (v2.5.2)                                        |
| `/_QUERIES/{location}/{script}`                                                                  | Token (also required when `queries.restrict = true`) + script ACL |
| `/_QUERIES/registry/...`                                                                         | Token + `queries.register_admins`                                 |
| `/_mcp`                                                                                          | Token                                                             |
| `/_PLUGIN/{file}/{func}`                                                                         | Token (v2.5.2)                                                    |
| `/auth`, `/_health`, `/_ready`, `/_studio`                                                       | Public                                                            |

A request with no token gets **401** `{"error":"authorization token is empty"}`.

With `auth.enabled = false`, none of these routes require a token. `/_mcp` and `/_PLUGIN` are then open to any caller; CRUD, catalog, and `/show` still follow [`[access]`](https://docs.prestd.com/get-started/permissions.md). To require a token on every route regardless, set `jwt.default = true` (below).

### Required verification material

When `jwt.default = true` and debug mode is off, you should configure one of the following:

| Setting            | Environment variable     | Purpose                                                                                              |
| ------------------ | ------------------------ | ---------------------------------------------------------------------------------------------------- |
| `jwt.key`          | `PREST_JWT_KEY`          | Shared secret for HMAC algorithms — minimum length applies, see [below](#hmac-key-requirements-v242) |
| `jwt.jwks`         | `PREST_JWT_JWKS`         | JSON Web Key Set for asymmetric verification                                                         |
| `jwt.wellknownurl` | `PREST_JWT_WELLKNOWNURL` | OpenID Connect well-known URL to fetch JWKS                                                          |

**In v2+ (**[**#974**](https://github.com/prest/prest/pull/974)**):** if JWT is enabled but no verification material is configured, JWT middleware is **auto-disabled** with an error log — the server continues to start. When `auth.enabled = true` without `jwt.key`, auth is also auto-disabled.

> **v2.0.0-rc6 tagged binary:** the rc6 release **refuses to start** in the same situations. See [v2.0.0-rc6](https://docs.prestd.com/releases/v2.0.0-rc6.md#jwt-fail-closed-startup-960).

### HMAC key requirements (v2.4.2)

Since **v2.4.2** ([#1017](https://github.com/prest/prest/pull/1017)), pREST validates `jwt.key` against the RFC 7518 minimum for the configured HMAC algorithm at config load. The underlying library (`go-jose/v4`) enforces these sizes itself; checking at startup surfaces the problem in logs instead of at request time.

| `jwt.algo`                                          | Minimum `jwt.key` length                         |
| --------------------------------------------------- | ------------------------------------------------ |
| `HS256` — also the default when `jwt.algo` is unset | **32 bytes**                                     |
| `HS384`                                             | **48 bytes**                                     |
| `HS512`                                             | **64 bytes**                                     |
| `RS*`, `ES*`, `PS*`, `EdDSA`                        | Not checked — `jwt.key` is not used as a MAC key |

The check is on the byte length of the raw string, so a 32-character ASCII secret satisfies HS256. Measure yours with `printf '%s' "$PREST_JWT_KEY" | wc -c`.

{% hint style="danger" %}
**An undersized key fails open, not closed.** pREST starts normally, discards the key, and disables the features that need it. `POST /auth` is no longer registered (clients get **404**, not 401) and every route wrapped by the auth middleware **passes through unauthenticated**. With `jwt.default = true` and no JWKS, the JWT middleware is removed from the stack entirely.

Rotate short secrets **before** upgrading, and check startup logs for:

```
level=ERROR msg="jwt.key too short for HMAC algorithm" algo=HS256 got=6 want=32
level=ERROR msg="auth disabled: jwt.key is empty"
```

{% endhint %}

A configured `jwt.jwks` or `jwt.wellknownurl` is unaffected — verification continues against the JWKS even when an undersized HMAC key is discarded.

### Signature algorithm (`jwt.algo`, v2.4.2)

`jwt.algo` was accepted but discarded in earlier v2 releases — tokens were parsed without restricting the permitted signature algorithm. Since **v2.4.2** it is passed to the parser as the single allowed algorithm, which structurally prevents algorithm-confusion attacks.

* A token whose `alg` header does not match `jwt.algo` is rejected with **401** and `{"error": "failed JWT token parser"}`.
* The value is matched **case-sensitively** against `EdDSA`, `HS256`, `HS384`, `HS512`, `RS256`, `RS384`, `RS512`, `ES256`, `ES384`, `ES512`, `PS256`, `PS384`, `PS512`. Anything else — including `hs256` in lowercase or an explicit `algo = ""` — makes every request return **HTTP 500** with `unsupported JWT signature algorithm`.

Leave `jwt.algo` unset to get the `HS256` default.

### JWKS fetch hardening (v2.3.0)

When you configure `jwt.wellknownurl` / `PREST_JWT_WELLKNOWNURL`, pREST fetches the JWKS from the identity provider. Since **v2.3.0** ([#1002](https://github.com/prest/prest/pull/1002)), that fetch (now on `jwx/v3`):

* **Rejects non-2xx responses** instead of attempting to parse an error page.
* **Caps the response body at 1 MiB** to bound memory.
* **Redacts the URL in logs** — userinfo, query string, and fragment are dropped.

Key-matching semantics (kid match, single-key with empty kid, empty-HMAC-key bypass guard) are unchanged, and there are **no config or environment changes**: `jwt.jwks` and `jwt.wellknownurl` work exactly as before.

Debug mode (`PREST_DEBUG=true` or `debug = true` in TOML) bypasses JWT enforcement at runtime.

To disable JWT entirely, leave `jwt.default = false` (the default in v2+).

### Whitelist

Endpoints matching the whitelist regex do not require a JWT. The v2 default whitelist is `^\/auth$` (only the `/auth` endpoint). Configure additional patterns in TOML or with `PREST_JWT_WHITELIST`. Setting `jwt.whitelist` replaces the default, so keep `^\/auth$` in the list:

```toml
[jwt]
whitelist = ["^\\/auth$", "^\\/ping$", "^\\/ping\\/.*$"]
```

The same list can be set with `PREST_JWT_WHITELIST`. Separate the patterns with spaces:

```sh
PREST_JWT_WHITELIST="^/auth$ ^/_health$ ^/_ready$"
```

In Docker Compose, write `$$` for each `$`, because Compose interpolates `$` in values:

```yaml
environment:
  PREST_JWT_WHITELIST: "^/auth$$ ^/_health$$ ^/_ready$$"
```

{% hint style="danger" %}
Do not write `PREST_JWT_WHITELIST` as a JSON array or with commas. pREST splits the value on spaces only, and each piece is a regular expression, so:

* A compact JSON array, such as `["^/auth$","^/_health$"]`, becomes one pattern. Go reads its `[...]` as a character class that matches any path containing `/`, so the JWT check is skipped on every route.
* A JSON array with spaces, such as `["^/auth$", "^/_health$"]`, leaves the first piece `["^/auth$",` as an invalid pattern, and every request returns **500**.
* Commas, such as `^/auth$,^/_health$`, make one pattern that matches nothing, so every route, including `/auth`, still requires a token.
  {% endhint %}

From v2.5.2 the whitelist is also how you re-expose a catalog route on purpose, for example a public schema browser:

```toml
[jwt]
whitelist = ["^\\/auth$", "^\\/tables$"]
```

{% hint style="warning" %}
Whitelisting `/databases`, `/schemas`, `/tables`, or `/show/...` lets anonymous callers map your schema again — the exposure fixed by [GHSA-fhf5-m388-4w4p](https://github.com/prest/prest/security/advisories/GHSA-fhf5-m388-4w4p). Table ACL from `[access]` still applies to whitelisted routes.
{% endhint %}

#### Health and readiness probes

With `jwt.default = true` and debug mode off, the JWT middleware runs for every route, so `/_health` and `/_ready` answer **401** to a probe that sends no token. To let a probe through, add its path to `jwt.whitelist` in TOML, and keep `^/auth$` in the list:

```toml
[jwt]
whitelist = ["^/auth$", "^/_health$", "^/_ready$"]
```

* The whitelist matches against the path and query string. `^/_health$` does not match `/_health?x=1`, so add a pattern for each query form a probe sends, or leave the query out of the probe URL.
* Whitelisted `/_health` and `/_ready` answer any caller, but they report only up or down: a failed check returns **503** with `{"error":"database unavailable"}` and no driver or alias detail, `/_health` returns **200** with `{"adapter":"<name>"}` naming the adapter, and `/_ready` returns **200** with no body.
* The list can also be set with `PREST_JWT_WHITELIST`, using the space-separated form shown in [Whitelist](#whitelist).
* This is a configuration choice. It does not change pREST's defaults or behaviour, and it is not tied to a release.

### Upgrading from v1

v1 used `[/auth]` as the default whitelist and did not enforce JWT key configuration at startup. See [Upgrading to v2](https://docs.prestd.com/get-started/upgrading-to-v2.md) for migration steps.

***

## Token generation (`/auth` endpoint)

When `auth.enabled = true`, pREST exposes a `/auth` endpoint that validates credentials against a database table and returns a signed JWT.

By default the token expires six hours after it is issued. To change that, set `auth.token_ttl` (`PREST_AUTH_TOKEN_TTL`) to a duration such as `30m` or `12h`, or to a number of seconds — see [Configuring pREST — Auth](https://docs.prestd.com/get-started/configuring-prest.md#auth).

Available from v2.6.0 ([#1097](https://github.com/prest/prest/pull/1097)). Before v2.6.0, tokens always lasted six hours.

### Bearer

```sh
curl -i -X POST http://127.0.0.1:3000/auth -H "Content-Type: application/json" -d '{"username": "<username>", "password": "<password>"}'
```

### Basic

```sh
curl -i -X POST http://127.0.0.1:3000/auth --user "<username>:<password>"
```

### Creating users (`prestd auth create-user`)

Available from v2.6.0 ([#1102](https://github.com/prest/prest/pull/1102)). Before v2.6.0, insert the row yourself with a password hashed for `auth.encrypt`, as [Deploying with Docker](https://docs.prestd.com/deployment/deploying-with-docker.md#with-docker-compose) shows.

`prestd auth create-user` adds a user that can log in through `/auth`. It reads the same config as the server (`auth.schema`, `auth.table`, `auth.username`, `auth.password` and `auth.encrypt`), so the stored row is exactly what `/auth` checks, on PostgreSQL and on MySQL.

```sh
# Prompts for the password twice, without echo
prestd auth create-user alice --name "Alice" --metadata '{"role":"admin"}'

# From a script or a secret store
printf '%s' "$ALICE_PASSWORD" | prestd auth create-user alice --password-stdin
```

```
created user "alice" (id 1)
```

| Flag               | Effect                                                                                 |
| ------------------ | -------------------------------------------------------------------------------------- |
| `--password-stdin` | Read the password from stdin. One trailing newline is dropped                          |
| `--name`           | Stored in the `name` column                                                            |
| `--metadata`       | A JSON document stored in the `metadata` column and returned in `user_info` by `/auth` |

* There is no `--password` flag, so passwords stay out of shell history and process listings. Without a terminal and without `--password-stdin`, the command stops with `stdin is not a terminal: pipe the password in and pass --password-stdin`.
* The password is hashed with `auth.encrypt`: a bcrypt hash by default, or a hex digest for `MD5` and `SHA1`. bcrypt rejects a password longer than 72 bytes.
* The username is trimmed and stored in lower case, as `/auth` lowercases the username it looks up. `ALICE` and `alice` log in as the same user.
* `name` and `metadata` are written only when set, so an auth table without those columns still takes users.
* A taken username fails with `create user: user already exists: alice`. An empty username or password, or `--metadata` that is not JSON, also fails.
* The auth table must exist. prestd creates it on startup when `auth.enabled = true`, and on PostgreSQL `prestd migrate up auth` creates it too.

## Related

* [Configuring pREST — JWT](https://docs.prestd.com/get-started/configuring-prest.md#jwt)
* [v2.4.2 release notes](https://docs.prestd.com/releases/v2.4.2.md)
* [v2.5.2 release notes](https://docs.prestd.com/releases/v2.5.2.md)
* [MCP over HTTP](https://docs.prestd.com/get-started/mcp-over-http.md)
* [Install pREST MCP Adapter](https://docs.prestd.com/ai/install-prest-mcp.md)
* [Permissions](https://docs.prestd.com/get-started/permissions.md)
* [Acronyms](https://docs.prestd.com/readme/acronyms.md) · [JWT](https://docs.prestd.com/readme/acronyms.md#jwt) · [MCP](https://docs.prestd.com/readme/acronyms.md#mcp)
