Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(jwt): Support custom secret keys for signing JWTs #3546

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/utils/jwt/jws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,10 @@
throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')
}
if (isCryptoKey(key)) {
if (key.type !== 'private') {
throw new Error(`unexpected non private key: CryptoKey.type is ${key.type}`)
if (key.type !== 'private' && key.type !== 'secret') {
throw new Error(
`unexpected key type: CryptoKey.type is ${key.type}, expected private or secret`
)

Check warning on line 56 in src/utils/jwt/jws.ts

View check run for this annotation

Codecov / codecov/patch

src/utils/jwt/jws.ts#L54-L56

Added lines #L54 - L56 were not covered by tests
}
return key
}
Expand Down
42 changes: 42 additions & 0 deletions src/utils/jwt/jwt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,48 @@ describe('JWT', () => {
expect(err instanceof JwtTokenSignatureMismatched).toBe(true)
})

it('sign & verify & decode with a custom secret', async () => {
const payload = { message: 'hello world' }
const algorithm = {
name: 'HMAC',
hash: {
name: 'SHA-256',
},
}
const secret = await crypto.subtle.importKey(
'raw',
Buffer.from('cefb73234d5fae4bf27662900732b52943e8d53e871fe0f353da95de4599c21d', 'hex'),
algorithm,
false,
['sign', 'verify']
)
const tok = await JWT.sign(payload, secret)
const expected =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.qunGhchNXH_unqWXN6hB0Elhzr5SykSXVhklLti1aFI'
expect(tok).toEqual(expected)

const verifiedPayload = await JWT.verify(tok, secret)
expect(verifiedPayload).not.toBeUndefined()
expect(verifiedPayload).toEqual(payload)

const invalidSecret = await crypto.subtle.importKey(
'raw',
Buffer.from('cefb73234d5fae4bf27662900732b52943e8d53e871fe0f353da95de41111111', 'hex'),
algorithm,
false,
['sign', 'verify']
)
let err = null
let authorized
try {
authorized = await JWT.verify(tok, invalidSecret)
} catch (e) {
err = e
}
expect(authorized).toBeUndefined()
expect(err instanceof JwtTokenSignatureMismatched).toBe(true)
})

const rsTestCases = [
{
alg: AlgorithmTypes.RS256,
Expand Down
Loading