Skip to content
Myr

feat(jwt): add `JwtTokenInvalid` object as `cause` when JWT is invalid (#2448)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* feat(jwt): add `JwtTokenInvalid` object as `cause` when JWT is invalid * denoify

authored by Yusuke Wada · committed by GitHub · parent 021329f · Browse files · 3 files+37 added−8 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+37 added−8 removed

  • tests:+27 added−0 removed
  • other:+10 added−8 removed

3 files+37 added−8 removed

modified:deno_dist/middleware/jwt/index.ts+5 added-4 removed
modified:src/middleware/jwt/index.test.ts+27 added
1import { Hono } from '../../hono'2import { HTTPException } from '../../http-exception'3import { jwt } from '.'45describe('JWT', () => {6 describe('Credentials in header', () => {
207 unmodified lines
214 )215 expect(handlerExecuted).toBeFalsy()216 })217 })218219 describe('Error handling with `cause`', () => {220 const app = new Hono()221222 app.use('/auth/*', jwt({ secret: 'a-secret' }))223 app.get('/auth/*', (c) => c.text('Authorized'))224225 app.onError((e, c) => {226 if (e instanceof HTTPException && e.cause instanceof Error) {227 return c.json({ name: e.cause.name, message: e.cause.message }, 401)228 }229 return c.text(e.message, 401)230 })231232 it('Should not authorize', async () => {233 const credential = 'abc.def.ghi'234 const req = new Request('http://localhost/auth')235 req.headers.set('Authorization', `Bearer ${credential}`)236 const res = await app.request(req)237 expect(res.status).toBe(401)238 expect(await res.json()).toEqual({239 name: 'JwtTokenInvalid',240 message: `invalid JWT token: ${credential}`,241 })242 })243 })244})
modified:src/middleware/jwt/index.ts+5 added-4 removed
59 unmodified lines
60 })61 }6263 let payload64 let msg = ''64 let cause65 try {66 payload = await Jwt.verify(token, options.secret, options.alg)67 } catch (e) {68 msg = `${e}`68 cause = e69 }70 if (!payload) {71 throw new HTTPException(401, {72 message: msg,72 message: 'Unauthorized',73 res: unauthorizedResponse({74 ctx,75 error: 'invalid_token',76 statusText: msg,76 statusText: 'Unauthorized',77 errDescription: 'token verification failure',78 }),79 cause,80 })81 }8283 ctx.set('jwtPayload', payload)
23 unmodified lines