跳至內容

基本身份驗證中介軟體

此中介軟體可將基本身份驗證套用至指定路徑。使用 Cloudflare Workers 或其他平台實作基本身份驗證比看起來更複雜,但使用此中介軟體,一切都變得輕而易舉。

如需更多關於基本身份驗證方案底層運作方式的資訊,請參閱 MDN 文件

匯入

ts
import { Hono } from 'hono'
import { basicAuth } from 'hono/basic-auth'

使用方式

ts
const app = new Hono()

app.use(
  '/auth/*',
  basicAuth({
    username: 'hono',
    password: 'acoolproject',
  })
)

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

限制於特定路由 + 方法

ts
const app = new Hono()

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

app.delete(
  '/auth/page',
  basicAuth({ username: 'hono', password: 'acoolproject' }),
  (c) => {
    return c.text('Page deleted')
  }
)

如果您想自行驗證使用者,請指定 verifyUser 選項;回傳 true 表示接受。

ts
const app = new Hono()

app.use(
  basicAuth({
    verifyUser: (username, password, c) => {
      return (
        username === 'dynamic-user' && password === 'hono-password'
      )
    },
  })
)

選項

必要 username: string

正在驗證的使用者名稱。

必要 password: string

用於驗證所提供使用者名稱的密碼值。

選用 realm: string

領域的網域名稱,作為傳回的 WWW-Authenticate 質詢標頭的一部分。預設值為 "Secure Area"
查看更多:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate#directives

選用 hashFunction: Function

用於處理密碼安全比較的雜湊函式。

選用 verifyUser: (username: string, password: string, c: Context) => boolean | Promise<boolean>

用於驗證使用者的函式。

選用 invalidUserMessage: string | object | MessageFunction

MessageFunction(c: Context) => string | object | Promise<string | object>。如果使用者無效,則顯示自訂訊息。

更多選項

選用 ...users: { username: string, password: string }[]

範例

定義多個使用者

此中介軟體也允許您傳遞任意參數,其中包含定義更多 usernamepassword 配對的物件。

ts
app.use(
  '/auth/*',
  basicAuth(
    {
      username: 'hono',
      password: 'acoolproject',
      // Define other params in the first object
      realm: 'www.example.com',
    },
    {
      username: 'hono-admin',
      password: 'super-secure',
      // Cannot redefine other params here
    },
    {
      username: 'hono-user-1',
      password: 'a-secret',
      // Or here
    }
  )
)

或較不硬式編碼

ts
import { users } from '../config/users'

app.use(
  '/auth/*',
  basicAuth(
    {
      realm: 'www.example.com',
      ...users[0],
    },
    ...users.slice(1)
  )
)

以 MIT 授權條款發佈。