I am trying to add authentication using a JWT strategy.
I have just protected one endpoint for testing purpose. Even though I am providing a token, it's apparently malformed.
console.log
{
err: null,
user: false,
info: JsonWebTokenError {
name: 'JsonWebTokenError',
message: 'jwt malformed'
}
}
Here is how I am signing this token:
async signIn(
authCredentialsInput: AuthCredentialsInput,
): Promise<AccessToken> {
const { email, password } = authCredentialsInput
const athlete = await this.athleteRepository.findByEmail(email)
if (!athlete) throw new UnauthorizedException('no user')
if (await this.isWrongPassword(password, athlete.password))
throw new UnauthorizedException('wrong password')
const payload = { athleteId: athlete.id }
const token = this.jwtService.sign(payload)
return { token }
}
I can't grasp what I've done wrong. Any thoughts?
EDIT 2:
How I add the the token to the authorization header:
function expectCorrectGqlResponse(
mutation: Query,
retrievedDataKey: string,
expectedData: Record<string, unknown> | Array<Record<string, unknown>>,
) {
const GRAPHQL_URL = '/graphql'
console.warn(token)
return request(app.getHttpServer())
.post(GRAPHQL_URL)
.set('Authorization', 'Bearer ' + token)
.send(mutation)
.expect((response: any) => {
displayErrors(response)
const retrievedData = response.body.data[retrievedDataKey]
expect(retrievedData).toStrictEqual(expectedData)
})
}
How I validate the token:
async validate(payload: any) {
console.log(payload)
return { athleteId: payload.athleteId }
}