Merge pull request #3090 from Human-Connection/2202_do_not_encode_the_entire_user_in_bearer_token

fix(jwt): Whitelist encoded JWT attributes
This commit is contained in:
mattwr18 2020-02-18 14:37:15 +01:00 committed by GitHub
commit 44d503c53c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 67 additions and 5 deletions

View File

@ -3,14 +3,12 @@ import CONFIG from './../config'
// Generate an Access Token for the given User ID
export default function encode(user) {
const token = jwt.sign(user, CONFIG.JWT_SECRET, {
const { id, name, slug } = user
const token = jwt.sign({ id, name, slug }, CONFIG.JWT_SECRET, {
expiresIn: '1d',
issuer: CONFIG.GRAPHQL_URI,
audience: CONFIG.CLIENT_URI,
subject: user.id.toString(),
})
// jwt.verifySignature(token, CONFIG.JWT_SECRET, (err, data) => {
// console.log('token verification:', err, data)
// })
return token
}

View File

@ -0,0 +1,62 @@
import encode from './encode'
import jwt from 'jsonwebtoken'
import CONFIG from './../config'
describe('encode', () => {
let payload
beforeEach(() => {
payload = {
name: 'Some body',
slug: 'some-body',
id: 'some-id',
}
})
it('encodes a valided JWT bearer token', () => {
const token = encode(payload)
expect(token.split('.')).toHaveLength(3)
const decoded = jwt.verify(token, CONFIG.JWT_SECRET)
expect(decoded).toEqual({
name: 'Some body',
slug: 'some-body',
id: 'some-id',
sub: 'some-id',
aud: expect.any(String),
iss: expect.any(String),
iat: expect.any(Number),
exp: expect.any(Number),
})
})
describe('given sensitive data', () => {
beforeEach(() => {
payload = {
...payload,
email: 'none-of-your-business@example.org',
password: 'topsecret',
}
})
it('does not encode sensitive data', () => {
const token = encode(payload)
expect(payload).toEqual({
email: 'none-of-your-business@example.org',
password: 'topsecret',
name: 'Some body',
slug: 'some-body',
id: 'some-id',
})
const decoded = jwt.verify(token, CONFIG.JWT_SECRET)
expect(decoded).toEqual({
name: 'Some body',
slug: 'some-body',
id: 'some-id',
sub: 'some-id',
aud: expect.any(String),
iss: expect.any(String),
iat: expect.any(Number),
exp: expect.any(Number),
})
})
})
})

View File

@ -192,7 +192,9 @@ describe('login', () => {
data: { login: token },
} = await mutate({ mutation: loginMutation, variables })
jwt.verify(token, CONFIG.JWT_SECRET, (err, data) => {
expect(data.email).toEqual('test@example.org')
expect(data).toMatchObject({
id: 'acb2d923-f3af-479e-9f00-61b12e864666',
})
expect(err).toBeNull()
done()
})