Skip to content
Myr

jwt.ts

This file

Path

src/middleware/jwt/jwt.ts

190 lines · 5.9 KiB · TypeScript

Last changed by

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–31why, one step back
1/**
2 * @module3 * JWT Auth Middleware for Hono.4 */56import type { Context } from '../../context'7import { getCookie, getSignedCookie } from '../../helper/cookie'8import { HTTPException } from '../../http-exception'9import type { MiddlewareHandler } from '../../types'10import type { CookiePrefixOptions } from '../../utils/cookie'11import { Jwt } from '../../utils/jwt'12import '../../context'13import type { SignatureAlgorithm } from '../../utils/jwt/jwa'14import type { SignatureKey } from '../../utils/jwt/jws'15import type { VerifyOptions } from '../../utils/jwt/jwt'1617// eslint-disable-next-line @typescript-eslint/no-explicit-any18export type JwtVariables<T = any> = {19 jwtPayload: T20}2122/**23 * JWT Auth Middleware for Hono.24 *25 * @see {@link https://hono.dev/docs/middleware/builtin/jwt}26 *27 * @param {object} options - The options for the JWT middleware.28 * @param {SignatureKey} options.secret - A value of your secret key.29 * @param {string} [options.cookie] - If this value is set, then the value is retrieved from the cookie header using that value as a key, which is then validated as a token.30 * @param {SignatureAlgorithm} options.alg - An algorithm type that is used for verifying (required). Available types are `HS256` | `HS384` | `HS512` | `RS256` | `RS384` | `RS512` | `PS256` | `PS384` | `PS512` | `ES256` | `ES384` | `ES512` | `EdDSA`.31 * @param {string} [options.headerName='Authorization'] - The name of the header to look for the JWT token. Default is 'Authorization'.

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 32why, one step back
32 * @param {string} [options.realm] - The protection space described by the `realm` parameter of the returned `WWW-Authenticate` challenge header. Defaults to the request URL.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 33–60why, one step back
33 * @param {VerifyOptions} [options.verification] - Additional options for JWT payload verification.
34 * @returns {MiddlewareHandler} The middleware handler function.35 *36 * @example37 * ```ts38 * const app = new Hono()39 *40 * app.use(41 * '/auth/*',42 * jwt({43 * secret: 'it-is-very-secret',44 * alg: 'HS256',45 * headerName: 'x-custom-auth-header', // Optional, default is 'Authorization'46 * })47 * )48 *49 * app.get('/auth/page', (c) => {50 * return c.text('You are authorized')51 * })52 * ```53 */54export const jwt = (options: {55 secret: SignatureKey56 cookie?:57 | string58 | { key: string; secret?: string | BufferSource; prefixOptions?: CookiePrefixOptions }59 alg: SignatureAlgorithm60 headerName?: string

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 61why, one step back
61 realm?: string

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 62–92why, one step back
62 verification?: VerifyOptions
63}): MiddlewareHandler => {64 const verifyOpts = options.verification || {}6566 if (!options || !options.secret) {67 throw new Error('JWT auth middleware requires options for "secret"')68 }6970 if (!options.alg) {71 throw new Error('JWT auth middleware requires options for "alg"')72 }7374 if (!crypto.subtle || !crypto.subtle.importKey) {75 throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')76 }7778 return async function jwt(ctx, next) {79 const headerName = options.headerName || 'Authorization'8081 const credentials = ctx.req.raw.headers.get(headerName)82 let token83 if (credentials) {84 const parts = credentials.split(/\s+/)85 if (parts.length !== 2 || parts[0].toLowerCase() !== 'bearer') {86 const errDescription = 'invalid credentials structure'87 throw new HTTPException(401, {88 message: errDescription,89 res: unauthorizedResponse({90 ctx,91 error: 'invalid_request',92 errDescription,

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 93why, one step back
93 realm: options.realm,

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 94–129why, one step back
94 }),
95 })96 } else {97 token = parts[1]98 }99 } else if (options.cookie) {100 if (typeof options.cookie == 'string') {101 token = getCookie(ctx, options.cookie)102 } else if (options.cookie.secret) {103 if (options.cookie.prefixOptions) {104 token = await getSignedCookie(105 ctx,106 options.cookie.secret,107 options.cookie.key,108 options.cookie.prefixOptions109 )110 } else {111 token = await getSignedCookie(ctx, options.cookie.secret, options.cookie.key)112 }113 } else {114 if (options.cookie.prefixOptions) {115 token = getCookie(ctx, options.cookie.key, options.cookie.prefixOptions)116 } else {117 token = getCookie(ctx, options.cookie.key)118 }119 }120 }121122 if (!token) {123 const errDescription = 'no authorization included in request'124 throw new HTTPException(401, {125 message: errDescription,126 res: unauthorizedResponse({127 ctx,128 error: 'invalid_request',129 errDescription,

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 130why, one step back
130 realm: options.realm,

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 131–152why, one step back
131 }),
132 })133 }134135 let payload136 let cause137 try {138 payload = await Jwt.verify(token, options.secret, {139 alg: options.alg,140 ...verifyOpts,141 })142 } catch (e) {143 cause = e144 }145 if (!payload) {146 throw new HTTPException(401, {147 message: 'Unauthorized',148 res: unauthorizedResponse({149 ctx,150 error: 'invalid_token',151 statusText: 'Unauthorized',152 errDescription: 'token verification failure',

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 153why, one step back
153 realm: options.realm,

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 154–169why, one step back
154 }),
155 cause,156 })157 }158159 ctx.set('jwtPayload', payload)160161 await next()162 }163}164165function unauthorizedResponse(opts: {166 ctx: Context167 error: string168 errDescription: string169 statusText?: string

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 170why, one step back
170 realm?: string

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 171why, one step back
171}) {

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

lines 172–177why, one step back
172 // `realm` and `error_description` end up inside a quoted-string, so any `"`
173 // they contain has to be escaped or the header is cut short. Same handling as174 // the bearer-auth middleware.175 const realm = (opts.realm ?? opts.ctx.req.url).replace(/"/g, '\\"')176 const errDescription = opts.errDescription.replace(/"/g, '\\"')177

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 178–181why, one step back
178 return new Response('Unauthorized', {
179 status: 401,180 statusText: opts.statusText,181 headers: {

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 182why, one step back
182 'WWW-Authenticate': `Bearer realm="${realm}",error="${opts.error}",error_description="${errDescription}"`,

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 183–190why, one step back
183 },
184 })185}186187export const verifyWithJwks = Jwt.verifyWithJwks188export const verify = Jwt.verify189export const decode = Jwt.decode190export const sign = Jwt.sign