feat(jwt): support for getting payload from `c.get('jwtPayload')` (#1025)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent c503436 · Browse files · 6 files·+67 added−36 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+67 added−36 removed
- tests:+35 added−26 removed
- other:+32 added−10 removed
Provenance
- Commit
e6669f7- Tree
aeff31a- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
c503436
6 files changed+67 added−36 removed
modified:deno_dist/middleware/jwt/index.ts+13 added-3 removed
123456789101112131415161735 unmodified lines535455564957585952606162635664656667682 unmodified lines717273747576777879import { HTTPException } from '../../http-exception.ts'import type { MiddlewareHandler } from '../../types.ts'import { Jwt } from '../../utils/jwt/index.ts'import type { AlgorithmTypes } from '../../utils/jwt/types.ts'import '../../context.ts'
declare module '../../context.ts' { interface ContextVariableMap { // eslint-disable-next-line @typescript-eslint/no-explicit-any jwtPayload: any }}
export const jwt = (options: { secret: string cookie?: string alg?: string35 unmodified lines }) throw new HTTPException(401, { res }) }
let authorized = false let payload let msg = '' try { authorized = await Jwt.verify(token, options.secret, options.alg as AlgorithmTypes) payload = await Jwt.verify(token, options.secret, options.alg as AlgorithmTypes) } catch (e) { msg = `${e}` } if (!authorized) { if (!payload) { const res = new Response('Unauthorized', { status: 401, statusText: msg, headers: {2 unmodified lines }) throw new HTTPException(401, { res }) }
ctx.set('jwtPayload', payload)
await next() }}modified:deno_dist/utils/jwt/jwt.ts+3 added-2 removed
110 unmodified lines111 export const verify = async (112 token: string,113 secret: string,114 alg: AlgorithmTypes = AlgorithmTypes.HS256115+ // eslint-disable-next-line @typescript-eslint/no-explicit-any115-): Promise<boolean> => {116+): Promise<any> => {117 const tokenParts = token.split('.')118 if (tokenParts.length !== 3) {119 throw new JwtTokenInvalid(token)120 }16 unmodified lines137 if (encodedSignature !== tokenParts[2]) {138 throw new JwtTokenSignatureMismatched(token)139 }140 140- return true141+ return payload142 }143 144 // eslint-disable-next-line145 export const decode = (token: string): { header: any; payload: any } => {12 unmodified linesmodified:src/middleware/jwt/index.test.ts+15 added-10 removed
18 unmodified lines19 })20 21 app.get('/auth/*', (c) => {22 handlerExecuted = true23- return c.text('auth')23+ const payload = c.get('jwtPayload')24+ return c.json(payload)25 })26 app.get('/auth-unicode/*', (c) => {27 handlerExecuted = true27- return c.text('auth')28+ const payload = c.get('jwtPayload')29+ return c.json(payload)30 })31 app.get('/nested/*', (c) => {32 handlerExecuted = true31- return c.text('auth')33+ const payload = c.get('jwtPayload')34+ return c.json(payload)35 })36 37 it('Should not authorize', async () => {38 const req = new Request('http://localhost/auth/a')11 unmodified lines50 req.headers.set('Authorization', `Bearer ${credential}`)51 const res = await app.request(req)52 expect(res).not.toBeNull()53 expect(res.status).toBe(200)51- expect(await res.text()).toBe('auth')54+ expect(await res.json()).toEqual({ message: 'hello world' })55 expect(handlerExecuted).toBeTruthy()56 })57 58 it('Should authorize Unicode', async () => {4 unmodified lines63 req.headers.set('Authorization', `Basic ${credential}`)64 const res = await app.request(req)65 expect(res).not.toBeNull()66 expect(res.status).toBe(200)64- expect(await res.text()).toBe('auth')67+ expect(await res.json()).toEqual({ message: 'hello world' })68 expect(handlerExecuted).toBeTruthy()69 })70 71 it('Should not authorize Unicode', async () => {42 unmodified lines114 req.headers.set('Authorization', `Bearer ${credential}`)115 const res = await app.request(req)116 expect(res).not.toBeNull()117 expect(res.status).toBe(200)115- expect(await res.text()).toBe('auth')118+ expect(await res.json()).toEqual({ message: 'hello world' })119 expect(handlerExecuted).toBeTruthy()120 })121 })122 10 unmodified lines133 app.use('/auth-unicode/*', jwt({ secret: 'a-secret', cookie: 'access_token' }))134 135 app.get('/auth/*', (c) => {136 handlerExecuted = true134- return c.text('auth')137+ const payload = c.get('jwtPayload')138+ return c.json(payload)139 })140 app.get('/auth-unicode/*', (c) => {141 handlerExecuted = true138- return c.text('auth')142+ const payload = c.get('jwtPayload')143+ return c.json(payload)144 })145 146 it('Should not authorize', async () => {147 const req = new Request('http://localhost/auth/a')14 unmodified lines162 }),163 })164 const res = await app.request(req)165 expect(res).not.toBeNull()161- expect(await res.text()).toBe('auth')166+ expect(await res.json()).toEqual({ message: 'hello world' })167 expect(res.status).toBe(200)168 expect(handlerExecuted).toBeTruthy()169 })170 8 unmodified lines179 })180 const res = await app.request(req)181 expect(res).not.toBeNull()182 expect(res.status).toBe(200)178- expect(await res.text()).toBe('auth')183+ expect(await res.json()).toEqual({ message: 'hello world' })184 expect(handlerExecuted).toBeTruthy()185 })186 187 it('Should not authorize Unicode', async () => {30 unmodified linesmodified:src/middleware/jwt/index.ts+13 added-3 removed
123456789101112131415161735 unmodified lines535455564957585952606162635664656667682 unmodified lines717273747576777879import { HTTPException } from '../../http-exception'import type { MiddlewareHandler } from '../../types'import { Jwt } from '../../utils/jwt'import type { AlgorithmTypes } from '../../utils/jwt/types'import '../../context'
declare module '../../context' { interface ContextVariableMap { // eslint-disable-next-line @typescript-eslint/no-explicit-any jwtPayload: any }}
export const jwt = (options: { secret: string cookie?: string alg?: string35 unmodified lines }) throw new HTTPException(401, { res }) }
let authorized = false let payload let msg = '' try { authorized = await Jwt.verify(token, options.secret, options.alg as AlgorithmTypes) payload = await Jwt.verify(token, options.secret, options.alg as AlgorithmTypes) } catch (e) { msg = `${e}` } if (!authorized) { if (!payload) { const res = new Response('Unauthorized', { status: 401, statusText: msg, headers: {2 unmodified lines }) throw new HTTPException(401, { res }) }
ctx.set('jwtPayload', payload)
await next() }}modified:src/utils/jwt/jwt.test.ts+20 added-16 removed
29 unmodified lines30 it('JwtTokenInvalid', async () => {31 const tok = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ'32 const secret = 'a-secret'33 let err: JwtTokenInvalid34- let authorized = false34+ let authorized35 try {36 authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)37 } catch (e) {38 err = e as JwtTokenInvalid39 }40 // @ts-ignore41 expect(err).toEqual(new JwtTokenInvalid(tok))42- expect(authorized).toBe(false)42+ expect(authorized).toBeUndefined()43 })44 45 it('JwtTokenNotBefore', async () => {46 const tok =47 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2NjQ2MDYzMzQsImV4cCI6MTY2NDYwOTkzNCwibmJmIjoiMzEwNDYwNjI2NCJ9.hpSDT_cfkxeiLWEpWVT8TDxFP3dFi27q1K7CcMcLXHc'48 const secret = 'a-secret'49 let err: JwtTokenNotBefore50- let authorized = false50+ let authorized51 try {52 authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)53 } catch (e) {54 err = e as JwtTokenNotBefore55 }56 // @ts-ignore57 expect(err).toEqual(new JwtTokenNotBefore(tok))58- expect(authorized).toBe(false)58+ expect(authorized).toBeUndefined()59 })60 61 it('JwtTokenExpired', async () => {62 const tok =63 'eyJraWQiOiJFemF6bVZWbnd0TUpUNEFveFVtT0dILWJ0Y2VUVFM3djBYcEJuMm5ZZ2VjIiwiYWxnIjoiSFMyNTYifQ.eyJyb2xlIjoiYXBpX3JvbGUiLCJleHAiOjE2MzMwNDY0MDB9.Gmq_dozOnwzqkMUMEm7uny7cMZuF1d0QkCnmRXAbTEk'64 const secret = 'a-secret'65 let err66- let authorized = false66+ let authorized67 try {68 authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)69 } catch (e) {70 err = e71 }72 expect(err).toEqual(new JwtTokenExpired(tok))73- expect(authorized).toBe(false)73+ expect(authorized).toBeUndefined()74 })75 76 it('JwtTokenIssuedAt', async () => {77 const now = 16330464004 unmodified lines82 const secret = 'a-secret'83 const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)84 85 let err86- let authorized = false86+ let authorized87 try {88 authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)89 } catch (e) {90 err = e91 }92 expect(err).toEqual(new JwtTokenIssuedAt(now, iat))93- expect(authorized).toBe(false)93+ expect(authorized).toBeUndefined()94 })95 96 it('HS256 sign & verify & decode', async () => {97 const payload = { message: 'hello world' }2 unmodified lines100 const expected =101 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'102 expect(tok).toEqual(expected)103 104- expect(await JWT.verify(tok, secret, AlgorithmTypes.HS256)).toBe(true)104+ const verifiedPayload = await JWT.verify(tok, secret, AlgorithmTypes.HS256)105+ expect(verifiedPayload).not.toBeUndefined()106+ expect(verifiedPayload).toEqual(payload)107 108 expect(JWT.decode(tok)).toEqual({109 header: {110 alg: 'HS256',13 unmodified lines124 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'125 expect(tok).toEqual(expected)126 127 let err = null126- let authorized = false128+ let authorized129 try {130 authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)131 } catch (e) {132 err = e133 }132- expect(authorized).toBe(false)134+ expect(authorized).toBeUndefined()135 expect(err instanceof JwtTokenSignatureMismatched).toBe(true)136 })137 138 it('HS512 sign & verify & decode', async () => {3 unmodified lines142 const expected =143 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.RqVLgExB_GXF1-9T-k4V4HjFmiuQKTEjVSiZd-YL0WERIlywZ7PfzAuTZSJU4gg8cscGamQa030cieEWrYcywg'144 expect(tok).toEqual(expected)145 144- expect(await JWT.verify(tok, secret, AlgorithmTypes.HS512)).toBe(true)146+ const verifiedPayload = await JWT.verify(tok, secret, AlgorithmTypes.HS512)147+ expect(verifiedPayload).not.toBeUndefined()148+ expect(verifiedPayload).toEqual(payload)149 150 expect(JWT.decode(tok)).toEqual({151 header: {152 alg: 'HS512',13 unmodified lines166 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.RqVLgExB_GXF1-9T-k4V4HjFmiuQKTEjVSiZd-YL0WERIlywZ7PfzAuTZSJU4gg8cscGamQa030cieEWrYcywg'167 expect(tok).toEqual(expected)168 169 let err = null166- let authorized = false170+ let authorized171 try {172 authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)173 } catch (e) {174 err = e175 }172- expect(authorized).toBe(false)176+ expect(authorized).toBeUndefined()177 expect(err instanceof JwtTokenSignatureMismatched).toBe(true)178 })179 180 it('HS384 sign & verify', async () => {4 unmodified lines185 'eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.C1Br1183Oy6O7th4NDCOaI9WB75i3FMCuYlv1tCL9HggsU89T-SNutghwhJykD3r'186 expect(tok).toEqual(expected)187 188 let err = null185- let authorized = false189+ let authorized190 try {191 authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)192 } catch (e) {193 err = e194 }191- expect(authorized).toBe(false)195+ expect(authorized).toBeUndefined()196 expect(err instanceof JwtTokenSignatureMismatched).toBe(true)197 })198 })modified:src/utils/jwt/jwt.ts+3 added-2 removed
110 unmodified lines111 export const verify = async (112 token: string,113 secret: string,114 alg: AlgorithmTypes = AlgorithmTypes.HS256115+ // eslint-disable-next-line @typescript-eslint/no-explicit-any115-): Promise<boolean> => {116+): Promise<any> => {117 const tokenParts = token.split('.')118 if (tokenParts.length !== 3) {119 throw new JwtTokenInvalid(token)120 }16 unmodified lines137 if (encodedSignature !== tokenParts[2]) {138 throw new JwtTokenSignatureMismatched(token)139 }140 140- return true141+ return payload142 }143 144 // eslint-disable-next-line145 export const decode = (token: string): { header: any; payload: any } => {12 unmodified lines