0
0
mirror of https://github.com/honojs/hono.git synced 2024-12-01 11:51:01 +01:00
hono/deno_dist/middleware/jwt/index.ts
Yusuke Wada d00a47ef70 feat: introduce HTTPException (#796)
* feat: introduce `HTTPException`

* denoify and fixed tests for Lagon
2023-01-19 22:45:25 +09:00

70 lines
2.1 KiB
TypeScript

import type { MiddlewareHandler } from '../../types.ts'
import { HTTPException } from '../../utils/http-exception.ts'
import { Jwt } from '../../utils/jwt/index.ts'
import type { AlgorithmTypes } from '../../utils/jwt/types.ts'
export const jwt = (options: {
secret: string
cookie?: string
alg?: string
}): MiddlewareHandler => {
if (!options) {
throw new Error('JWT auth middleware requires options for "secret')
}
if (!crypto.subtle || !crypto.subtle.importKey) {
throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')
}
return async (ctx, next) => {
const credentials = ctx.req.headers.get('Authorization')
let token
if (credentials) {
const parts = credentials.split(/\s+/)
if (parts.length !== 2) {
const res = new Response('Unauthorized', {
status: 401,
headers: {
'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="invalid credentials structure"`,
},
})
throw new HTTPException(401, { res })
} else {
token = parts[1]
}
} else if (options.cookie) {
token = ctx.req.cookie(options.cookie)
}
if (!token) {
const res = new Response('Unauthorized', {
status: 401,
headers: {
'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="no authorization included in request"`,
},
})
throw new HTTPException(401, { res })
}
let authorized = false
let msg = ''
try {
authorized = await Jwt.verify(token, options.secret, options.alg as AlgorithmTypes)
} catch (e) {
msg = `${e}`
}
if (!authorized) {
const res = new Response('Unauthorized', {
status: 401,
statusText: msg,
headers: {
'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_token",error_description="token verification failure"`,
},
})
throw new HTTPException(401, { res })
}
await next()
}
}