PostGraphile JWT guide
JWTs are optional in PostGraphile. You can authenticate users with session
cookies, API keys, mTLS, or any other mechanism that lets your web framework
identify who is making the request. The key requirement is that you surface
the relevant details to PostgreSQL via
pgSettings so that Row Level Security (RLS)
policies and functions can make decisions. See the
security page for the broader architecture and trade-offs.
在 PostGraphile 中,JWT 并非必选项。你可以使用会话 Cookie、API 密钥、双向 TLS(mTLS)或任何其他能够让 Web 框架识别请求发起者身份的认证机制。核心要求只有一个:通过 pgSettings 将相关的身份信息传递给 PostgreSQL,以便行级安全性(RLS)策略和数据库函数据此做出权限判断。关于整体架构设计及各类方案的权衡,请参阅安全性文档。
Assuming that you choose to use JWTs to provide authentication to PostGraphile
(and the author would encourage you to consider alternatives), this guide
explains how JWTs fit into that picture, how to populate pgSettings from a
verified token, and when you might lean on the postgraphile/presets/lazy-jwt
convenience preset.
如果你最终决定使用 JWT 为 PostGraphile 提供身份认证(尽管作者仍鼓励你考虑其他替代方案),本指南将为你说明 JWT 在整个认证流程中的定位、如何从已验证的令牌中提取信息并填充到 pgSettings,以及在什么情况下可以借助便捷的 postgraphile/presets/lazy-jwt preset。
You are expected to verify tokens in your server framework (Express, Koa,
Fastify, etc.) and feed the resulting claims to PostGraphile via the
preset.grafast.context callback's pgSettings property. This means you can
implement refresh tokens, revocation, clock skew handling, and other behaviours
that PostGraphile cannot reasonably guess for you.
你需要在服务端框架(如 Express、Koa、Fastify 等)中自行完成令牌验证,再通过 preset.grafast.context 回调返回的 pgSettings 属性将解析出的声明(claim)传入 PostGraphile。这意味着你可以自由实现刷新令牌、令牌吊销、时钟偏差处理以及其他 PostGraphile 无法替你预判的定制逻辑。
Typical request flow典型请求流程
-
Your web framework receives the request and runs whichever authentication middleware you have chosen (sessions, JWTs, mutual TLS, etc.).
Web 框架接收请求,并执行你所选用的认证中间件(如会话、JWT、双向 TLS 等)。
-
After verification you extract the claims you want PostgreSQL to know about and pass them into
pgSettingsviapreset.grafast.context.验证通过后,从中提取需要让 PostgreSQL 获知的声明(claim),并通过
preset.grafast.context传入pgSettings。 -
PostgreSQL reads those values with
current_setting(...)inside policies and functions, completing the authorization story.PostgreSQL 在策略和函数内部通过
current_setting(...)读取这些值,从而完成整套鉴权链路。
For JWT-based setups the first step is often done with
jsonwebtoken, jose, or vendor
SDKs. The second step is where PostGraphile comes in.
在基于 JWT 的架构中,第一步通常借助 jsonwebtoken、jose 或第三方厂商提供的 SDK 完成,而第二步正是 PostGraphile 发挥作用的地方。
Populating pgSettings after verifying a JWT在验证 JWT 后填充 pgSettings
Below is an Express-flavoured example that validates a Bearer token and exposes select claims to PostgreSQL.
下面是一个基于 Express 的示例,演示了如何校验 Bearer 令牌并将选定的声明暴露给 PostgreSQL:
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
import { verify } from "jsonwebtoken";
const preset: GraphileConfig.Preset = {
extends: [PostGraphileAmberPreset],
grafast: {
async context(requestContext, args) {
const req = requestContext.expressv4?.req;
const header = req?.get("authorization") ?? "";
const [, token] = header.split(" ");
const pgSettings = {
...args.contextValue?.pgSettings,
} as Record<string, string>;
if (token) {
try {
const claims = verify(token, process.env.JWT_SECRET!, {
audience: "postgraphile",
algorithms: ["HS256"],
});
if (typeof claims === "object" && claims !== null) {
if (claims.role && typeof claims.role === "string") {
pgSettings.role = claims.role;
}
for (const [key, value] of Object.entries(claims)) {
if (typeof value === "undefined" || value === null) continue;
if (!/^[a-z_][a-z0-9_]*$/i.test(key) || key.length > 52) continue;
pgSettings[`jwt.claims.${key}`] = String(value);
}
}
} catch (e) {
// Let the framework decide how to surface auth errors.
requestContext.expressv4?.res?.status(401);
throw e;
}
}
return {
...args.contextValue,
pgSettings,
};
},
},
};
export default preset;
Key points:
要点说明:
-
You decide which claims to trust and forward. You might strip or rename values, or merge in data from a session store.
由你决定信任并透传哪些声明——你可以剔除或重命名字段,也可以合并来自会话存储(session store)的数据。
-
Anything placed inside
pgSettingsbecomes available viacurrent_setting('...', true)when RLS policies run.凡是放入
pgSettings中的键值,在 RLS 策略执行时都可以通过current_setting('...', true)获取。 -
Do not leak entire JWT payloads blindly—only forward what your database schema needs.
切勿盲目透传整个 JWT payload,只应转发数据库 schema 实际需要的字段。
If you want to understand how claims map onto PostgreSQL session variables, see the JWT specification for the precise rules.
如果想了解声明如何映射到 PostgreSQL 会话变量,请参阅 JWT 规范了解精确规则。
Supplying JWTs from clients在客户端传递 JWT
Clients typically send JWTs via the Authorization header using the Bearer
scheme:
客户端通常采用 Bearer 认证方式,通过 Authorization 请求头发送 JWT:
Authorization: Bearer JWT_TOKEN_HERE
Below are a few JavaScript client examples; adapt them to your own stack.
以下是几个常见的 JavaScript 客户端示例,你可以根据自己的技术栈进行调整。
Apollo Client (v3, HTTP)Apollo Client(v3,HTTP 请求)
const httpLink = createHttpLink({
uri: "/graphql",
});
const authLink = setContext((_, { headers }) => {
const token = getJWTToken();
return {
headers: {
...headers,
...(token ? { authorization: `Bearer ${token}` } : null),
},
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
If you are using Apollo Client 3 with graphql-ws for subscriptions:
如果你在使用 Apollo Client 3 时结合 graphql-ws 实现订阅功能:
import { GraphQLWsLink } from "@apollo/client/link/subscriptions";
import { createClient } from "graphql-ws";
const token = getJWTToken();
const wsLink = new GraphQLWsLink(
createClient({
url: "ws://localhost:3000/graphql",
connectionParams: token
? { authorization: `Bearer ${token}` }
: {},
}),
);
See the Apollo authentication docs and the subscriptions guide for additional configuration options.
更多配置选项请参阅 Apollo 身份认证文档和订阅功能指南。
Relay (Modern)Relay(Modern 版)
function fetchQuery(operation, variables) {
const token = getJWTToken();
return fetch("/graphql", {
method: "POST",
headers: {
"content-type": "application/json",
authorization: token ? `Bearer ${token}` : "",
},
body: JSON.stringify({
query: operation.text,
variables,
}),
}).then((response) => response.json());
}
const environment = new Environment({
network: Network.create(fetchQuery),
store: new Store(new RecordSource()),
});
Relay’s network layer setup is documented in the Relay guides.
关于 Relay 网络层的配置方式,可参阅 Relay 官方指南。
About the lazy-jwt preset关于 lazy-jwt preset
postgraphile/presets/lazy-jwt exists for teams that need a quick stopgap while
building a real authentication layer. When enabled it:
postgraphile/presets/lazy-jwt 旨在为正在搭建正式认证层的团队提供一套快速过渡方案。启用该 preset 后,它会:
-
runs only when you use a
grafservHTTP adaptor;仅在使用
grafservHTTP 适配器时运行; -
reads the
Authorizationheader for Bearer tokens fromrequestContext.node?.req?.headers?.authorization(thus only works with adaptors that populate this, such aspostgraphile/grafserv/express/v4);从
requestContext.node?.req?.headers?.authorization读取Authorization请求头中的 Bearer 令牌(因此仅适用于会填充该字段的适配器,例如postgraphile/grafserv/express/v4); -
verifies the token with
jsonwebtokenusing a shared secret (set viapreset.grafserv.pgJwtSecretorpreset.schema.pgJwtSecret), default algorithmsHS256/HS384, and default audiencepostgraphile(override viapreset.grafserv.pgJwtVerifyOptions);使用
jsonwebtoken和共享密钥(通过preset.grafserv.pgJwtSecret或preset.schema.pgJwtSecret配置)验证令牌,默认允许的签名算法为HS256/HS384,默认受众(audience)为postgraphile(可通过preset.grafserv.pgJwtVerifyOptions覆盖); -
copies the
roleclaim and alphanumeric claims intopgSettingsunder thejwt.claims.*namespace.将
role声明以及字母数字格式的声明复制到pgSettings中,归入jwt.claims.*命名空间下。
It does not handle refresh tokens, key rotation, token revocation, custom
claim mapping, or multi-tenant secret lookup. Treat it as a temporary measure
and plan to replace it with middleware that explicitly sets pgSettings.
它不会处理刷新令牌、密钥轮换、令牌吊销、自定义声明映射或多租户密钥查询。请仅将其视为临时过渡手段,并尽早替换为显式设置 pgSettings 的自定义中间件。
Issuing JWTs from PostgreSQL从 PostgreSQL 签发 JWT
If you want to generate JWTs from your PostgreSQL schema, PostGraphile can sign
composite types listed in preset.gather.pgJwtTypes. When a function returns
one of those types the response will instead include a signed JWT string (signed
using the preset.schema.pgJwtSecret and any preset.schema.pgJwtSignOptions).
Combine that with your own authentication SQL to issue tokens. Remember that
this feature does not manage refresh tokens or provide a complete auth system—
it only signs the composite payloads you return.
如果你希望在 PostgreSQL schema 中直接生成 JWT,PostGraphile 可以对 preset.gather.pgJwtTypes 中列出的复合类型进行签名。当数据库函数返回其中任一复合类型时,响应结果将被替换为经过签名的 JWT 字符串(使用 preset.schema.pgJwtSecret 及 preset.schema.pgJwtSignOptions 进行签名)。你可以将其与自定义的 SQL 认证逻辑结合来签发令牌。但请记住,该特性并不会管理刷新令牌,也不是一套完整的认证系统——它仅仅负责对你返回的复合类型 payload 进行签名。
Choosing between JWTs and alternatives如何在 JWT 与替代方案之间做选择
JWTs are one option amongst many. Session cookies, OAuth-backed passport
strategies, or bespoke API keys all work as long as you populate pgSettings
appropriately. The
pgSettings section of the config docs
shows how to expose request data regardless of authentication style, and the
security page lists common approaches. Pick the strategy that
fits your infrastructure, and make sure you're aware of the trade-offs of each
approach.
JWT 只是众多选择之一。无论是会话 Cookie、基于 OAuth 的 Passport 认证策略,还是自定义的 API 密钥,只要正确填充 pgSettings,都能与 PostGraphile 完美配合。你可以参阅配置文档中的 pgSettings 章节,了解如何为各种认证方式透传请求信息;也可以阅读安全性页面了解常见方案对比。请结合自身基础设施选择最合适的策略,并充分了解每种方案的权衡利弊。