Skip to main content

PostGraphile JWT/JWK Verification QuickstartPostGraphile JWT/JWK 验证快速入门

This guide adapts Auth0’s Node (Express) quickstart so that the verified JWT payload is forwarded to PostgreSQL through pgSettings. It assumes you are running PostGraphile using the Express adaptor (postgraphile/grafserv/express/v4), but similar will apply for alternative servers.

本指南基于 Auth0 的 Node(Express)快速入门 改写,演示如何通过 pgSettings 将验证后的 JWT payload 传递给 PostgreSQL。文中示例假定你使用 Express 适配器(postgraphile/grafserv/express/v4)运行 PostGraphile,其他服务端框架的实现思路也基本一致。

Terms:

相关术语:

Processing a JWT is a middleware concernJWT 处理属于中间件层的职责

Your web framework middleware will handle verification, refresh tokens, revocation lists, and other security concerns - the logic here is not specific to PostGraphile. Once you have a set of trusted claims you can expose them to PostgreSQL through PostGraphile's pgSettings function. See the JWT guide for the bigger picture and the PostgreSQL JWT specification for how claims map onto PostgreSQL session settings.

JWT 的验签、令牌刷新、吊销列表校验及其他安全逻辑均应由 Web 框架的中间件负责处理——这部分逻辑并不局限于 PostGraphile 本身。一旦获得受信任的声明(claims),即可通过 PostGraphile 的 pgSettings 函数将其暴露给 PostgreSQL。关于整体方案设计,请参阅 JWT 指南;关于声明如何映射为 PostgreSQL 会话设置,请参阅 PostgreSQL JWT 规范。

Dependencies安装依赖​

This walkthrough uses Express and the Auth0-maintained helpers:

本示例使用 Express 以及 Auth0 官方维护的辅助库:

Install them with the package manager of your choice:

使用你习惯的包管理器安装这些依赖:

npm install --save express express-jwt jwks-rsa

Configure express-jwt配置 express-jwt​

express-jwt verifies the Bearer token and populates req.auth with the JWT payload. Configure it with your Auth0 details and JWKS endpoint:

express-jwt 会校验 Bearer 令牌,并将解码后的 JWT payload 写入 req.auth。请按你的 Auth0 应用信息与 JWKS 端点对其进行配置:

auth0.ts
import jwt from "express-jwt";
import jwksRsa from "jwks-rsa";

export const checkJwt = jwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://YOUR_DOMAIN/.well-known/jwks.json`,
}),
audience: "YOUR_API_IDENTIFIER",
issuer: `https://YOUR_DOMAIN/`,
algorithms: ["RS256"],
});

Surface trusted claims to PostgreSQL将受信任的声明传递至 PostgreSQL​

Inside preset.grafast.context copy whichever details you need into pgSettings. Only forward the fields your policies rely on.

在 preset.grafast.context 中,将所需的字段复制到 pgSettings 里。注意只转发你的数据库安全策略实际依赖的字段。

graphile.config.ts
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";

const preset: GraphileConfig.Preset = {
extends: [PostGraphileAmberPreset],

grafast: {
async context(requestContext, args) {
const req = requestContext.expressv4?.req;
const pgSettings = {
...args.contextValue?.pgSettings,
} as Record<string, string>;

const claims = req?.auth;
if (claims && typeof claims === "object") {
if (typeof claims.scope === "string") {
pgSettings["jwt.claims.scope"] = claims.scope;
}
if (typeof claims.sub === "string") {
pgSettings["jwt.claims.sub"] = claims.sub;
}
if (Array.isArray(claims.permissions)) {
pgSettings["jwt.claims.permissions"] = claims.permissions.join(" ");
}
}

return {
...args.contextValue,
pgSettings,
};
},
},
};

export default preset;

You can use alternative Postgres settings names, but ensure that you include at least one and at most two . characters, and that the text before the first . is not a scope reserved by PostgreSQL. Historically no-one has raised an issue with the jwt.claims prefix, so it seems to be a good choice.

你也可以使用其他的 Postgres 设置项名称,但需确保名称中至少包含 1 个、至多包含 2 个 . 字符,且第一个 . 之前的前缀不能是 PostgreSQL 的保留命名空间。长期以来 jwt.claims 前缀从未引发过冲突问题,因此是一个稳妥的选择。

Wire Express to Grafserv将 Express 与 Grafserv 接入​

Use the Auth0 middleware before adding PostGraphile to your express app.

在将 PostGraphile 挂载到 Express 应用之前,先注册 Auth0 鉴权中间件。

server.ts
import express from "express";
import { createServer } from "node:http";
import { grafserv } from "postgraphile/grafserv/express/v4";
import { postgraphile } from "postgraphile";

import preset from "./graphile.config.ts";
import { checkJwt } from "./auth0.ts";
import { authErrors } from "./auth-errors.ts";

const app = express();
const server = createServer(app);
server.on("error", (e) => void console.error(e));
app.use("/graphql", checkJwt, authErrors);

const pgl = postgraphile(preset);
const serv = pgl.createServ(grafserv);
serv
.addTo(app, server)
.then(() => {
const port = preset.grafserv?.port ?? 5678;
server.listen(port);
console.log(`GraphQL running at http://localhost:${port}/graphql`);
})
.catch((e) => {
console.error(e);
process.exit(1);
});

Error handling错误处理​

By default express-jwt sends HTML-formatted error pages. To keep errors inside the GraphQL response surface the UnauthorizedError as JSON:

默认情况下,express-jwt 会返回 HTML 格式的错误页面。为了让鉴权错误保持在 GraphQL 响应格式内,请将 UnauthorizedError 转换为 JSON 返回:

auth-errors.ts
import type { Request, Response, NextFunction } from "express";

export function authErrors(
err: any,
_req: Request,
res: Response,
next: NextFunction,
) {
if (err?.name === "UnauthorizedError") {
res.status(err.status ?? 401).json({ errors: [{ message: err.message }] });
return;
}
next(err);
}

Using the claims in PostgreSQL在 PostgreSQL 中使用这些声明​

Anything placed in pgSettings is available inside PostgreSQL via current_setting(...). For example:

所有写入 pgSettings 的键值对,在 PostgreSQL 内部都可以通过 current_setting(...) 读取。例如:

create function current_subject() returns text as $$
select nullif(current_setting('jwt.claims.sub', true), '');
$$ language sql stable;

You can reference the helper inside Row Level Security policies or use it in functions. Adjust the key names to match whatever you added to pgSettings.

你可以在行级安全策略(RLS)或数据库函数中引用这个辅助函数;如果自定义了键名,记得同步调整为与 pgSettings 中一致的键。

Once everything is wired up, PostGraphile simply consumes the claims you provide and enforces your database policies accordingly.

全部配置串联就绪后,PostGraphile 便会自动消费你传入的声明,并据此执行相应的数据库权限策略。


This article was originally written by BR, but has since been heavily modified and updated.

本文最初由 BR 撰写,后续经过了大量修订与更新。