jose
Provides JSON Web Signature and JSON Web Token APIs.
- Downloads / mo
- 878.5M
- Stars
- 7.9K
- Last release
- 6.2.17
- License
- MIT
Strengths
- Supports general JSON signatures. Use GeneralSign to produce a signed JSON JWS envelope.
- Imports existing PEM keys. Load supported public or private keys with the import helpers.
Limitations
- Algorithms depend on the runtime. Select an algorithm supported by the target runtime.
- Private keys start non-extractable. Set extractable when generated private keys must be exported.
Quickstart
import * as jose from "jose"; const { privateKey } = await jose.generateKeyPair("ES256"); const token = await new jose.SignJWT({ sub: "example" }) .setProtectedHeader({ alg: "ES256" }) .sign(privateKey); console.log(token);
jose examples
export async function signJWT( ctx: GenericEndpointContext, config: { options?: JwtOptions | undefined; payload: JWTPayloadWithOptional; /** Pre-resolved key from resolveSigningKey. Skips redundant DB lookup. */ resolvedKey?: ResolvedSigningKey; /** * Extra JWS Protected Header parameters to merge with the defaults * (`alg` and `kid`). Used by token profiles that require an explicit * media type, such as OIDC Back-Channel Logout's `typ: "logout+jwt"`. * * @see https://www.rfc-editor.org/rfc/rfc8725#section-3.11 */ header?: { typ?: string; cty?: string; }; /** * Optional override for the signing key. When set, looks up the key * by its `id` (matches the JWS `kid` header) via the JWKS adapter. * Throws if no key with that id exists. * * When unset, falls back to the most recently created key with the * primary `keyPairConfig.alg` (the historical default). */ signingKeyId?: string | undefined; /** * Optional override for the signing algorithm. Selects the most * recent key with this algorithm. When neither this nor * `signingKeyId` is set, the most recent key matching * `keyPairConfig.alg` is used (historical default). * * If both `signingKeyId` and `signingAlgorithm` are set, `signingKeyId` * wins; the algorithm is validated to match the resolved key and * the call throws on mismatch. */ signingAlgorithm?: JWSAlgorithms | undefined; }, ) { const { options } = config; const payload = config.payload as JWTPayload; // Iat const nowSeconds = Math.floor(Date.now() / 1000); const iat = payload.iat!; // Exp let exp = payload.exp; const defaultExp = toExpJWT( options?.jwt?.expirationTime ?? "15m", iat ?? nowSeconds, ); exp = exp ?? defaultExp; // Nbf const nbf = payload.nbf!; // Empty only for a direct `auth.api` call when no baseURL is configured const baseURLOrigin = typeof ctx.context.options.baseURL === "string" ? ctx.context.options.baseURL : ""; // Iss const iss = payload.iss; const defaultIss = options?.jwt?.issuer ?? baseURLOrigin; // Aud const aud = payload.aud; const defaultAud = options?.jwt?.audience ?? baseURLOrigin; if (!(iss ?? defaultIss) || !(aud ?? defaultAud)) { ctx.context.logger.warn( "[better-auth] The JWT plugin signed a JWT without an issuer or audience because no base URL was resolved for this call. Set `baseURL`, or `jwt.issuer` and `jwt.audience` in the JWT plugin options.", ); } // Custom/remote signing function if (options?.jwt?.sign) { const jwtPayload = { ...payload, iat, exp, nbf, iss: iss ?? defaultIss, aud: aud ?? defaultAud, }; // Forward extra protected-header parameters (e.g. `typ: "logout+jwt"`) // so profiles that require an explicit media type stay conformant even // with a remote signer. The signer still owns `alg`/`kid`. Also forward // per-call signing overrides as a third arg so remote KMS integrations // can honor per-resource kid/alg pinning. Both extra args are optional, // so existing single-arg implementations continue to work unchanged. return options.jwt.sign(jwtPayload, config.header, { signingKeyId: config.signingKeyId, signingAlgorithm: config.signingAlgorithm, }); } // Use pre-resolved key if available, otherwise resolve from DB with // any per-call overrides plumbed through. const { alg, kid, privateKey } = config.resolvedKey ?? (await resolveSigningKey(ctx, options, { signingKeyId: config.signingKeyId, signingAlgorithm: config.signingAlgorithm, }))!; const jwt = new SignJWT(payload) .setProtectedHeader({ // Spread caller header first so the resolved `alg`/`kid` always win. ...config.header, alg, kid, }) .setExpirationTime(exp) .setIssuer(iss ?? defaultIss) .setAudience(aud ?? defaultAud); if (iat) jwt.setIssuedAt(iat); if (payload.sub) jwt.setSubject(payload.sub); if (payload.nbf) jwt.setNotBefore(payload.nbf); if (payload.jti) jwt.setJti(payload.jti); return await jwt.sign(privateKey); }