JWT Auth ミドルウェア
JWT Auth ミドルウェアは、JWT トークンの検証によって認証を行います。 cookie オプションが未設定なら、Authorization ヘッダーを確認します。headerName オプションでヘッダー名を変更できます。
情報
クライアントが送信する Authorization ヘッダーには、指定された認証スキームが必要です。
例:Bearer my.token.value または Basic my.token.value
インポート
import { Hono } from 'hono'
import { jwt } from 'hono/jwt'
import type { JwtVariables } from 'hono/jwt'使い方
// Specify the variable types to infer the `c.get('jwtPayload')`:
type Variables = JwtVariables
const app = new Hono<{ Variables: Variables }>()
app.use(
'/auth/*',
jwt({
secret: 'it-is-very-secret',
alg: 'HS256',
})
)
app.get('/auth/page', (c) => {
return c.text('You are authorized')
})ペイロードを取得します。
const app = new Hono()
app.use(
'/auth/*',
jwt({
secret: 'it-is-very-secret',
alg: 'HS256',
verification: {
iss: 'my-trusted-issuer',
aud: 'my-api',
},
})
)
app.get('/auth/page', (c) => {
const payload = c.get('jwtPayload')
return c.json(payload) // eg: { "sub": "1234567890", "name": "John Doe", "iat": 1516239022, "iss": "my-trusted-issuer" }
})ヒント
jwt() は単なるミドルウェア関数です。環境変数(例:c.env.JWT_SECRET)を使いたい場合は、次のようにできます。
app.use('/auth/*', (c, next) => {
const jwtMiddleware = jwt({
secret: c.env.JWT_SECRET,
alg: 'HS256',
})
return jwtMiddleware(c, next)
})オプション
required secret: string
秘密鍵の値。
required alg: string
検証に使うアルゴリズムの型。
利用可能な型は HS256 | HS384 | HS512 | RS256 | RS384 | RS512 | PS256 | PS384 | PS512 | ES256 | ES384 | ES512 | EdDSA です。
optional cookie: string
設定すると、この値をキーとして cookie ヘッダーから値を取得し、トークンとして検証します。
optional headerName: string
JWT トークンを探すヘッダー名。デフォルトは Authorization です。
app.use(
'/auth/*',
jwt({
secret: 'it-is-very-secret',
alg: 'HS256',
headerName: 'x-custom-auth-header',
})
)optional realm: string
401 レスポンスで返す WWW-Authenticate チャレンジヘッダーの realm パラメーターで示す保護領域です。デフォルトはリクエスト URL です。
app.use(
'/auth/*',
jwt({
secret: 'it-is-very-secret',
realm: 'my-protected-api',
})
)optional verification: VerifyOptions
トークンの検証を制御するオプション。
optional VerifyOptions.iss: string | RegExp
トークンの検証で期待する発行者です。未設定なら iss クレームは検証されません。
optional VerifyOptions.aud: string | string[] | RegExp
トークンの検証で期待する対象者です。設定した場合、トークンには aud クレームが必要で、少なくとも 1 つの対象者の値が一致しなければなりません。
optional VerifyOptions.nbf: boolean
nbf(有効開始時刻)クレームが存在し、この値が true なら検証します。デフォルトは true です。
optional VerifyOptions.iat: boolean
iat(発行時刻)クレームが存在し、この値が true なら検証します。デフォルトは true です。
optional VerifyOptions.exp: boolean
exp(有効期限)クレームが存在し、この値が true なら検証します。デフォルトは true です。