fix(jwt): Encode only 3 attributes in JWT

This will prevent unintentional encoding of users email addresses in the
JWT.

@steffi201028 this might be interesting for you as well.
This commit is contained in:
roschaefer 2020-02-18 00:56:40 +01:00
parent 492427554b
commit e41a639cf1
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()
})