Skip to content

Bearer Auth 미들웨어

Bearer Auth 미들웨어는 요청 헤더에 포함된 API 토큰을 검증해 인증을 수행한다. 엔드포인트에 접근하는 HTTP 클라이언트는 Authorization 헤더에 Bearer {토큰} 값을 추가해야 한다.

터미널에서 curl 명령어를 사용할 때 다음과 같이 작성한다:

sh
curl -H 'Authorization: Bearer honoiscool' http://localhost:8787/auth/page

임포트

ts
import { Hono } from 'hono'
import { bearerAuth } from 'hono/bearer-auth'

사용 방법

NOTE

여러분의 token은 반드시 /[A-Za-z0-9._~+/-]+=*/ 정규식과 일치해야 한다. 그렇지 않으면 400 에러가 반환된다. 특히, 이 정규식은 URL-safe Base64와 표준 Base64로 인코딩된 JWT 모두를 허용한다. 이 미들웨어는 bearer 토큰이 JWT일 필요는 없으며, 위의 정규식과 일치하기만 하면 된다.

ts
const app = new Hono()

const token = 'honoiscool'

app.use('/api/*', bearerAuth({ token }))

app.get('/api/page', (c) => {
  return c.json({ message: 'You are authorized' })
})

특정 라우트와 메서드에만 제한하려면 다음과 같이 작성한다:

ts
const app = new Hono()

const token = 'honoiscool'

app.get('/api/page', (c) => {
  return c.json({ message: 'Read posts' })
})

app.post('/api/page', bearerAuth({ token }), (c) => {
  return c.json({ message: 'Created post!' }, 201)
})

여러 개의 토큰을 구현하려면 (예: 유효한 토큰은 읽기만 가능하고, 생성/수정/삭제는 특권 토큰으로 제한) 다음과 같이 작성한다:

ts
const app = new Hono()

const readToken = 'read'
const privilegedToken = 'read+write'
const privilegedMethods = ['POST', 'PUT', 'PATCH', 'DELETE']

app.on('GET', '/api/page/*', async (c, next) => {
  // 유효한 토큰 목록
  const bearer = bearerAuth({ token: [readToken, privilegedToken] })
  return bearer(c, next)
})
app.on(privilegedMethods, '/api/page/*', async (c, next) => {
  // 단일 유효 특권 토큰
  const bearer = bearerAuth({ token: privilegedToken })
  return bearer(c, next)
})

// GET, POST 등의 핸들러 정의

토큰 값을 직접 확인하고 싶다면 verifyToken 옵션을 지정한다. true를 반환하면 토큰이 승인된다.

ts
const app = new Hono()

app.use(
  '/auth-verify-token/*',
  bearerAuth({
    verifyToken: async (token, c) => {
      return token === 'dynamic-token'
    },
  })
)

옵션

필수 token: string | string[]

들어오는 bearer 토큰을 검증할 문자열이다.

optional realm: string

반환된 WWW-Authenticate 헤더의 일부로 사용되는 영역(domain name)의 이름. 기본값은 ""이다. 자세한 내용: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate#directives

optional prefix: string

Authorization 헤더 값의 접두사(또는 schema로도 알려짐). 기본값은 "Bearer"이다.

선택 사항 headerName: string

헤더 이름. 기본값은 Authorization이다.

optional hashFunction: Function

인증 토큰을 안전하게 비교하기 위한 해시 처리를 담당하는 함수이다.

optional verifyToken: (token: string, c: Context) => boolean | Promise<boolean>

토큰을 검증하는 함수.

optional noAuthenticationHeaderMessage: string | object | MessageFunction

MessageFunction(c: Context) => string | object | Promise<string | object> 타입이다. 인증 헤더가 없을 때 사용할 커스텀 메시지를 정의한다.

optional invalidAuthenticationHeaderMessage: string | object | MessageFunction

인증 헤더가 유효하지 않을 때 표시할 커스텀 메시지.

선택 사항 invalidTokenMessage: string | object | MessageFunction

토큰이 유효하지 않을 때 표시할 커스텀 메시지.

Released under the MIT License.