Skip to Content

JWT

Authenticate users with JWT tokens in services that can't use the session

The JWT plugin provides endpoints to retrieve a JWT token and a JWKS endpoint to verify the token.

This plugin is not meant as a replacement for the session. It's meant to be used for services that require JWT tokens. If you're looking to use JWT tokens for authentication, check out the Bearer Plugin.

The JWT plugin's /token endpoint and set-auth-jwt header produce JWKS-verifiable JWTs for external services. They are separate from Entro Auth's primary session_token cookie.

If you enable session.cookieCache.strategy = "jwt", the session_data cookie still uses HS256 with your Entro Auth secret by default. To make that cookie-cache JWT verifiable with the JWT plugin's JWKS too, set sessionCookieCache: true on jwt().

Installation

Add the plugin to your auth config

auth.ts
import { entroAuth } from "@entro314labs/entro-auth"
import { jwt } from "@entro314labs/entro-auth/plugins"

export const auth = entroAuth({
    plugins: [
        jwt(), 
    ]
})

Migrate the database

Run the migration or generate the schema to add the necessary fields and tables to the database.

npx @entro314labs/entro-auth-cli migrate

See the Schema section to add the fields manually.

Add the client plugin to your auth client

auth-client.ts
import { createAuthClient } from "@entro314labs/entro-auth/client"
import { jwtClient } from "@entro314labs/entro-auth/client/plugins"

export const authClient = createAuthClient({
  plugins: [
    jwtClient() 
  ]
})

Usage

Once you've installed the plugin, you can start using the JWT & JWKS plugin to get the token and the JWKS through their respective endpoints.

JWT

Retrieve the token

There are multiple ways to retrieve JWT tokens:

  1. Using the client plugin (recommended)
import { authClient } from "@/lib/auth-client"

const { data, error } = await authClient.token()
if (error) {
  // handle error
}
if (data) {
  const jwtToken = data.token
  // Use this token for authenticated requests to external services
}

This is the recommended approach for client applications that need JWT tokens for external API authentication.

An application that sends the token with every request to its own API should not ask for one each time. getJwt keeps the token until shortly before it runs out (renewBefore, 30 seconds by default), and calls made together share one request:

import { createAuthClient } from "@entro314labs/entro-auth/client"
import { jwtClient } from "@entro314labs/entro-auth/client/plugins"

export const authClient = createAuthClient({
  plugins: [jwtClient({ renewBefore: 30 })],
})

// wherever the API is called
const token = await authClient.getJwt()
if (token) {
  headers.set("Authorization", `Bearer ${token}`)
}

getJwt answers null when nobody is signed in and throws when the server cannot be asked: the two are not the same, and treating a failing server as "signed out" sends people to sign in for nothing. The client drops the kept token after every request of its own that changes something (signing in, signing out, revoking a session), since any of them can change who is signed in. It also drops it when the session the client holds comes to name someone else, or nobody: a sign-in or sign-out in another tab arrives that way, on a page that reads the session (useSession). Call forgetJwt() when your API refuses the token.

A token is good until it runs out, whatever happens to the session it was asked from: signing out, or revoking a session from another device, does not take back a token already issued. Keep expirationTime short (minutes) when the token is what your API trusts.

  1. Using your session token

To get the token, call the /token endpoint. This will return the following:

  { 
    "token": "ey..."
  }

Make sure to include the token in the Authorization header of your requests if the bearer plugin is added in your auth configuration.

await fetch("/api/auth/token", {
  headers: {
    "Authorization": `Bearer ${token}`
  },
})
  1. From set-auth-jwt header

When you call getSession method, a JWT is returned in the set-auth-jwt header, which you can use to send to your services directly.

The header is added to every getSession answer, and signing it reads the signing key from the database. With session.cookieCache on, that read is the only database round trip left in the request. If you do not read the header, set disableSettingJwtHeader: true.

import { authClient } from "@/lib/auth-client"

await authClient.getSession({
  fetchOptions: {
    onSuccess: (ctx)=>{
      const jwt = ctx.response.headers.get("set-auth-jwt")
    }
  }
})

Verifying the token

The token can be verified in your own service, without the need for an additional verify call or database check. For this JWKS is used. The public key can be fetched from the /api/auth/jwks endpoint.

Since this key is not subject to frequent changes, it can be cached indefinitely. The key ID (kid) that was used to sign a JWT is included in the header of the token. In case a JWT with a different kid is received, it is recommended to fetch the JWKS again.

On the auth server itself, auth.api.verifyJWT checks a token against the stored keys without a request:

const { payload } = await auth.api.verifyJWT({ body: { token } });
if (!payload) {
  // checked and refused: bad signature, expired, another issuer or audience
}

payload is null only for a token that was checked and refused. When the keys cannot be read, because the database is away or a custom getJwks throws, the call throws: nothing was checked, and treating that as "not valid" would sign everybody out during an outage. Answer it as a failure of your own service (a 503), not as a 401.

When the OAuth provider signs tokens with the JWT plugin, verifiers in the same process as the auth server read the keys directly instead of requesting /jwks, unless jwks.remoteUrl is set. These include the provider's introspection, revocation, and end-session endpoints, oauthProviderResourceClient(auth), and requireMcpAuth. The read skips the router, so hooks and rate limits on /jwks do not apply to it. Passing an explicit jwksUrl to oauthProviderResourceClient(auth) or requireMcpAuth fetches the keys over HTTP instead.

Access tokens are JWTs only when the client requests a resource and disableJwtPlugin is off. Otherwise they are opaque, and have no signing keys to read. When the OAuth provider runs in the same process, requireMcpAuth checks access tokens, opaque ones included, against its records. Given a jwksUrl, or without that provider, it verifies JWT signatures only. A separate resource server verifies opaque tokens by introspection with remoteVerify in oauthProviderResourceClient or createMcpProtectedRequestHandler.

  {
    "keys": [
        {
            "crv": "Ed25519",
            "x": "bDHiLTt7u-VIU7rfmcltcFhaHKLVvWFy-_csKZARUEU",
            "kty": "OKP",
            "kid": "c5c7995d-0037-4553-8aee-b5b620b89b23"
        }
    ]
  }

Example using jose with remote JWKS

import { jwtVerify, createRemoteJWKSet } from 'jose'

async function validateToken(token: string) {
  try {
    const JWKS = createRemoteJWKSet(
      new URL('http://localhost:3000/api/auth/jwks')
    )
    const { payload } = await jwtVerify(token, JWKS, {
      issuer: 'http://localhost:3000', // Should match your JWT issuer, which is the BASE_URL
      audience: 'http://localhost:3000', // Should match your JWT audience, which is the BASE_URL by default
    })
    return payload
  } catch (error) {
    console.error('Token validation failed:', error)
    throw error
  }
}

// Usage example
const token = 'your.jwt.token' // this is the token you get from the /api/auth/token endpoint
const payload = await validateToken(token)

Example with local JWKS

import { jwtVerify, createLocalJWKSet } from 'jose'


async function validateToken(token: string) {
  try {
    /**
     * This is the JWKS that you get from the /api/auth/
     * jwks endpoint
     */
    const storedJWKS = {
      keys: [{
        //...
      }]
    };
    const JWKS = createLocalJWKSet({
      keys: storedJWKS.data?.keys!,
    })
    const { payload } = await jwtVerify(token, JWKS, {
      issuer: 'http://localhost:3000', // Should match your JWT issuer, which is the BASE_URL
      audience: 'http://localhost:3000', // Should match your JWT audience, which is the BASE_URL by default
    })
    return payload
  } catch (error) {
    console.error('Token validation failed:', error)
    throw error
  }
}

// Usage example
const token = 'your.jwt.token' // this is the token you get from the /api/auth/token endpoint
const payload = await validateToken(token)

What a token does not tell you

A token is valid until it expires, 15 minutes by default, whatever happens to the session or the user meanwhile. A service that checks signature, issuer and audience accepts the token of someone who signed out, or whose account was deleted, for the rest of that time. If that matters, as it does when deleting an account has to end access at once, check that the user still exists before acting on the token. A service that shares the database with the auth server can look the user up by the sub claim. A service that exchanges the token for a session of its own can be told when the session here ends: see Account Events.

In an app that renders on the server, see the TanStack Start integration for keeping one token between the browser and the server instead of signing one per page.

OAuth Provider Mode

When you use the OAuth Provider or MCP plugin, disable both ways the JWT plugin hands session JWTs to the browser: the /token endpoint and the set-auth-jwt header. OAuth clients get tokens from /oauth2/token and claims from /oauth2/userinfo, so they need neither.

Session JWTs are signed with the same keys as OAuth access tokens, and by default they carry the auth server's URL as both iss and aud. A resource server that checks only signature, issuer, and audience can therefore accept a signed-in user's session JWT as an access token, without any client, consent, or scope. Disabling both paths removes that token from the browser. Resource servers should also reject tokens that are not OAuth access tokens; see Protect your API.

auth.ts
import { entroAuth } from "@entro314labs/entro-auth";
import { jwt } from "@entro314labs/entro-auth/plugins";

entroAuth({
  disabledPaths: [
    "/token",
  ],
  plugins: [jwt({
    disableSettingJwtHeader: true,
  })]
})

The OAuth provider requires both typ: "at+jwt" and the azp claim on JWT access tokens. This also applies when requireMcpAuth checks tokens against the provider in the same process. For signature verification on a resource server, pass typ: "at+jwt" in its verification options. See JWT or opaque tokens.

Remote JWKS Url

Disables the /jwks endpoint and uses this endpoint in any discovery such as OIDC.

Useful if your JWKS are not managed at /jwks or if your jwks are signed with a certificate and placed on your CDN.

NOTE: you MUST specify which asymmetric algorithm is used for signing.

auth.ts
jwt({
  jwks: {
    remoteUrl: "https://example.com/.well-known/jwks.json",
    keyPairConfig: {
      alg: 'ES256',
    },
  }
})

Custom JWKS Path

By default, the JWKS endpoint is available at /jwks. You can customize this path using the jwksPath option.

This is useful when you need to:

  • Follow OAuth 2.0/OIDC conventions (e.g., /.well-known/jwks.json)
  • Match existing API conventions in your application
  • Avoid path conflicts with other endpoints

Server Configuration:

auth.ts
jwt({
  jwks: {
    jwksPath: "/.well-known/jwks.json"
  }
})

Client Configuration:

When using a custom jwksPath on the server, you MUST configure the client with the same path:

auth-client.ts
import { createAuthClient } from "@entro314labs/entro-auth/client"
import { jwtClient } from "@entro314labs/entro-auth/client/plugins"

export const authClient = createAuthClient({
  plugins: [
    jwtClient({
      jwks: {
        jwksPath: "/.well-known/jwks.json" // Must match server configuration
      }
    })
  ]
})

Then you can use the jwks() method as usual:

const { data, error } = await authClient.jwks()
if (data) {
  // Use data.keys to verify JWT tokens
}

The jwksPath configured on the client MUST match the server configuration. If they don't match, the client will not be able to fetch the JWKS.

Custom Signing

This is an advanced feature. Configuration outside of this plugin MUST be provided.

Implementers:

  • remoteUrl must be defined if using the sign function. This shall store all active keys, not just the current one.
  • If using localized approach, ensure server uses the latest private key when rotated. Depending on deployment, the server may need to be restarted.
  • When using remote approach, verify the payload is unchanged after transit. Use integrity validation like CRC32 or SHA256 checks if available.
  • Apply the optional header argument to the signed header. It carries the typ a token profile requires, such as at+jwt for OAuth provider access tokens and logout+jwt for back-channel logout tokens. The OAuth provider rejects an access token without typ: at+jwt, and it logs a warning at startup when sign is set as a reminder.

Localized Signing

auth.ts
jwt({
  jwks: {
    remoteUrl: "https://example.com/.well-known/jwks.json",
    keyPairConfig: {
      alg: 'EdDSA',
    },
  },
  jwt: {
    sign: async (jwtPayload: JWTPayload, header) => {
      // this is pseudocode
      return await new SignJWT(jwtPayload)
        .setProtectedHeader({
          typ: "JWT",
          ...header,
          alg: "EdDSA",
          kid: process.env.currentKid,
        })
        .sign(process.env.clientPrivateKey);
    },
  },
})

Remote Signing

Useful if you are using a remote Key Management Service such as Google KMS, Amazon KMS, or Azure Key Vault.

auth.ts
jwt({
  jwks: {
    remoteUrl: "https://example.com/.well-known/jwks.json",
    keyPairConfig: {
      alg: 'ES256',
    },
  },
  jwt: {
    sign: async (jwtPayload: JWTPayload, header) => {
      // this is pseudocode
      const headers = JSON.stringify({ typ: 'JWT', ...header, kid: '123', alg: 'ES256' })
      const payload = JSON.stringify(jwtPayload)
      const encodedHeaders = Buffer.from(headers).toString('base64url')
      const encodedPayload = Buffer.from(payload).toString('base64url')
      const hash = createHash('sha256')
      const data = `${encodedHeaders}.${encodedPayload}`
      hash.update(Buffer.from(data))
      const digest = hash.digest()
      const sig = await remoteSign(digest)
      // integrityCheck(sig)
      const jwt = `${data}.${sig}`
      // verifyJwt(jwt)
      return jwt
    },
  },
})

Schema

The JWT plugin adds the following tables to the database:

JWKS

Table Name: jwks

Table
Field
Type
Attributes
Description
id
string
PK
Unique identifier for each web key
publicKey
string
-
The public part of the web key
privateKey
string
-
The private part of the web key
alg ?
string
-
The JWS algorithm this web key signs with
crv ?
string
-
The elliptic curve this web key was generated on
createdAt
Date
-
Timestamp of when the web key was created
expiresAt ?
Date
-
Timestamp of when the web key expires

You can customize the table name and fields for the jwks table. See the Database concept documentation for more information on how to customize plugin schema.

Options

Set sessionCookieCache to true to sign JWT session cookie cache values with the plugin's locally managed keys. This requires session.cookieCache.strategy to be set to "jwt".

auth.ts
jwt({
  sessionCookieCache: true
})

Algorithm of the Key Pair

The algorithm used for the generation of the key pair. The default is EdDSA with the Ed25519 curve. Below are the available options:

auth.ts
jwt({
  jwks: {
    keyPairConfig: {
      alg: "EdDSA",
      crv: "Ed25519"
    }
  }
})

EdDSA

  • Default Curve: Ed25519
  • Optional Property: crv
    • Available options: Ed25519, Ed448
    • Default: Ed25519

ES256

  • No additional properties

RSA256

  • Optional Property: modulusLength
    • Expects a number
    • Default: 2048

PS256

  • Optional Property: modulusLength
    • Expects a number
    • Default: 2048

ECDH-ES

  • Optional Property: crv
    • Available options: P-256, P-384, P-521
    • Default: P-256

ES512

  • No additional properties

ML-DSA-44, ML-DSA-65, ML-DSA-87

ML-DSA (RFC 9964) is a post-quantum signature. The JWKS publishes these keys with kty: "AKP".

  • No additional properties
  • Needs a runtime whose Web Crypto API supports ML-DSA: Node.js 24.7.0 or later, Deno 2.8.2 or later, or Cloudflare Workers with the webcrypto_modern_algorithms compatibility flag. On any other runtime the plugin refuses to start.
  • Every service that verifies the tokens needs an ML-DSA-capable JOSE library as well. To move them one at a time, keep a classical keyPairConfig and add ML-DSA to keyPairConfigs: both keys are published, and an OAuth protected resource can pin its tokens to ML-DSA with signingAlgorithm.
  • Tokens are large: an ML-DSA-65 signature alone is 3309 bytes, so a token is over 4 KB. With sessionCookieCache, the cookie is split across several cookies.
auth.ts
jwt({
  jwks: {
    keyPairConfig: { alg: "EdDSA" },
    keyPairConfigs: [{ alg: "ML-DSA-65" }],
  }
})

Disable private key encryption

By default, the private key is encrypted using AES256 GCM. You can disable this by setting the disablePrivateKeyEncryption option to true.

For security reasons, it's recommended to keep the private key encrypted.

auth.ts
jwt({
  jwks: {
    disablePrivateKeyEncryption: true
  }
})

Key Rotation

You can enable key rotation by setting the rotationInterval option. This will automatically rotate the key pair at the specified interval.

The default value is undefined (disabled).

auth.ts
jwt({
  jwks: {
    rotationInterval: 60 * 60 * 24 * 30, // 30 days
    gracePeriod: 60 * 60 * 24 * 30 // 30 days
  }
})
  • rotationInterval: The interval in seconds to rotate the key pair.
  • gracePeriod: The period in seconds to keep the old key pair valid after rotation. This is useful to allow clients to verify tokens signed by the old key pair. The default value is 30 days.

Modify JWT payload

By default the entire user object is added to the JWT payload. You can modify the payload by providing a function to the definePayload option.

auth.ts
jwt({
  jwt: {
    definePayload: ({user}) => {
      return {
        id: user.id,
        email: user.email,
        role: user.role
      }
    }
  }
})

Modify Issuer, Audience, Subject or Expiration time

If none is given, the BASE_URL is used as the issuer and the audience is set to the BASE_URL. The expiration time is set to 15 minutes.

Both are compared to the character, and baseURL is used exactly as written: https://example.com and https://example.com/ are two issuers. Two processes given the address with and without the trailing slash refuse every token of each other. When a token signed with this server's keys is refused for its issuer or audience, the plugin logs a warning that names both values.

Without a configured baseURL, direct auth.api calls have no issuer or audience to use, and the plugin logs a warning. Set baseURL, or set issuer and audience here.

auth.ts
jwt({
  jwt: {
    issuer: "https://example.com",
    audience: "https://example.com",
    expirationTime: "1h",
    getSubject: (session) => {
      // by default the subject is the user id
      return session.user.email
    }
  }
})

Custom Adapter

By default, the JWT plugin stores and retrieves JWKS from your database. You can provide a custom adapter to override this behavior, allowing you to store JWKS in alternative locations such as Redis, external services, or in-memory storage.

auth.ts
jwt({
  adapter: {
    getJwks: async (ctx) => {
      // Custom implementation to get all JWKS
      // This overrides the default database query
      return await yourCustomStorage.getAllKeys()
    },
    createJwk: async (ctx, webKey) => {
      // Custom implementation to create a new key
      // This overrides the default database insert
      return await yourCustomStorage.createKey(webKey)
    }
  }
})

When a verifier in the same process reads the keys, getJwks receives the request being verified in ctx.request and ctx.headers. That applies to introspection, revocation, end-session, and requireMcpAuth. oauthProviderResourceClient(auth) does not pass its request to getJwks, so there ctx carries only the auth context in ctx.context.

Because getJwks can return different keys for each request, such as per tenant, these verifiers do not cache its result. They call it on every verification, so cache inside your store if reads are expensive. Keep any such cache keyed by whatever your store selects keys by.

On this page