跳到内容
光环标志
光环基地

在后端验证用户的 JWT

您自己的后端可以仅使用项目 URL 检查请求是否来自已登录用户以及任何 JOSE 库。

操作指南6分钟 读取级别 中间

自此翻译以来,英文来源已发生变化。某些信息可能已过时。
该页面已自动翻译。英文版具有权威性。

How tokens are signed#

Each project has its own ES256 (ECDSA P-256) key. The access token header carries the kid of that key, and the claims carry:

  • iss: <project URL>/v1/auth (for example https://my-app-x1y2z3.aurabase.dev/v1/auth),
  • aud: the project identifier,
  • sub: the user id, plus role, email, app_metadata and user_metadata.

The public keys are served, without any API key, at <project URL>/.well-known/jwks.json. No secret is shared with your backend, and a token of one project is rejected by the keys of another.

Studio › Settings › API shows the JWKS URL, the issuer and the current kid.

Node.js (jose)#

import { createRemoteJWKSet, jwtVerify } from 'jose'

const projectUrl = process.env.NEXT_PUBLIC_AURABASE_URL! // https://<slug>.aurabase.dev
const PROJECT_ID = process.env.AURABASE_PROJECT_ID!

// jose caches the keys and refetches when it meets an unknown kid (rotation).
const jwks = createRemoteJWKSet(new URL(`${projectUrl}/.well-known/jwks.json`))

export async function verifyAccessToken(token: string) {
  const { payload } = await jwtVerify(token, jwks, {
    issuer: `${projectUrl}/v1/auth`,
    audience: PROJECT_ID,
    algorithms: ['ES256'],
  })
  return payload // payload.sub is the user id
}

Python (PyJWT)#

import os
import jwt  # pip install "pyjwt[crypto]"

projectUrl = os.environ["NEXT_PUBLIC_AURABASE_URL"]
PROJECT_ID = os.environ["AURABASE_PROJECT_ID"]
jwks = jwt.PyJWKClient(f"{projectUrl}/.well-known/jwks.json")

def verify_access_token(token: str) -> dict:
    key = jwks.get_signing_key_from_jwt(token).key
    return jwt.decode(
        token,
        key,
        algorithms=["ES256"],
        issuer=f"{projectUrl}/v1/auth",
        audience=PROJECT_ID,
    )

Go#

package main

import (
	"fmt"
	"os"

	"github.com/MicahParks/keyfunc/v3"
	"github.com/golang-jwt/jwt/v5"
)

func verify(token string) (jwt.MapClaims, error) {
	projectURL := os.Getenv("NEXT_PUBLIC_AURABASE_URL")
	jwks, err := keyfunc.NewDefault([]string{projectURL + "/.well-known/jwks.json"})
	if err != nil {
		return nil, err
	}
	claims := jwt.MapClaims{}
	_, err = jwt.ParseWithClaims(token, claims, jwks.Keyfunc,
		jwt.WithValidMethods([]string{"ES256"}),
		jwt.WithIssuer(projectURL+"/v1/auth"),
		jwt.WithAudience(os.Getenv("AURABASE_PROJECT_ID")),
	)
	if err != nil {
		return nil, fmt.Errorf("invalid token: %w", err)
	}
	return claims, nil
}

Key rotation#

Rotating the key in Studio (or with POST /v1/auth/admin/signing-keys/rotate and the service_role key) makes a new key sign every new token. The previous key stays in the JWKS for 24 hours, so tokens signed before the rotation keep verifying; a key that leaked can be revoked with DELETE /v1/auth/admin/signing-keys/<kid> once it is no longer the active one, and is then removed from the JWKS and refused.

信息

In the JavaScript SDK, aura.auth.getClaims() already verifies the session token locally with this JWKS and returns its real claims.

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ 报告问题