跳至內容

JWT 驗證中介軟體

JWT 驗證中介軟體透過使用 JWT 驗證令牌來提供身份驗證。如果未設定 cookie 選項,則中介軟體將檢查 Authorization 標頭。

資訊

從客戶端發送的 Authorization 標頭必須具有指定的方案。

範例:Bearer my.token.valueBasic my.token.value

匯入

ts
import { Hono } from 'hono'
import { jwt } from 'hono/jwt'
import type { JwtVariables } from 'hono/jwt'

用法

ts
// 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',
  })
)

app.get('/auth/page', (c) => {
  return c.text('You are authorized')
})

取得 Payload

ts
const app = new Hono()

app.use(
  '/auth/*',
  jwt({
    secret: 'it-is-very-secret',
  })
)

app.get('/auth/page', (c) => {
  const payload = c.get('jwtPayload')
  return c.json(payload) // eg: { "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }
})

提示

jwt() 僅是一個中介軟體函式。如果您想使用環境變數 (例如:c.env.JWT_SECRET),您可以如下使用

js
app.use('/auth/*', (c, next) => {
  const jwtMiddleware = jwt({
    secret: c.env.JWT_SECRET,
  })
  return jwtMiddleware(c, next)
})

選項

必要 secret: string

您的密鑰值。

如果設定此值,則會使用該值作為鍵,從 cookie 標頭中檢索值,然後將其驗證為令牌。

可選 alg: string

用於驗證的演算法類型。
預設值為 HS256

可用的類型為 HS256 | HS384 | HS512 | RS256 | RS384 | RS512 | PS256 | PS384 | PS512 | ES256 | ES384 | ES512 | EdDSA

在 MIT 授權下發布。