본문으로 건너뛰기
아우라베이스 로고
아우라베이스

백엔드에서 사용자의 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↗ 문제 신고