Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
test('#verifyToken verifies wrong JWT token and throws error', () => {
// given
const secret = 'test_secret';
const payload = { id: 'test_id' };
const token = generateToken({ secret: 'wrong_secret' })(payload);
const expectedError = new JsonWebTokenError('invalid signature');
type Payload = typeof payload;
// when
const verifiedToken = () => verifyToken({ secret })(token);
// then
expect(verifiedToken).toThrowError(expectedError);
});
async verifyAccessToken(accessToken: string) {
try {
// Don't return directly for catch block to work properly
const data = await jwtVerify(
accessToken,
config.auth.accessTokenSecret,
config.auth.verifyOptions
)
return data
} catch (err) {
if (err instanceof jwt.JsonWebTokenError || err instanceof SyntaxError) {
return null
}
throw err
}
},
}
verifyToken(token) {
if (token === null) {
return Bluebird.resolve(this.anonymous());
}
let decoded = null;
try {
decoded = jwt.verify(token, this.kuzzle.config.security.jwt.secret);
// probably forged token => throw without providing any information
if (!decoded._id) {
throw new jwt.JsonWebTokenError('Invalid token');
}
}
catch (err) {
if (err instanceof jwt.TokenExpiredError) {
return securityError.reject('expired');
}
if (err instanceof jwt.JsonWebTokenError) {
return securityError.reject('invalid');
}
return securityError.rejectFrom(err, 'verification_error', err.message);
}
return this.loadForUser(decoded._id, token)
.then(userToken => {
let tokenWithoutBearer = token;
if (token.slice(0, 6) === 'Bearer') {
tokenWithoutBearer = token.slice(7);
} else {
return errorUtil.ERROR({ error: 'Header include incorrect Bearer prefix' });
}
let payload;
try {
payload = jwt.verify(tokenWithoutBearer, this.configService.JWT_SECRET_KEY) as IJwtPayload | undefined;
} catch (error) {
if (error instanceof jwt.NotBeforeError) return errorUtil.ERROR({ error: 'Your Token Has Not Before' });
if (error instanceof jwt.TokenExpiredError) return errorUtil.ERROR({ error: 'Your Token Has Expired' });
if (error instanceof jwt.JsonWebTokenError) return errorUtil.ERROR({ error: 'Your Token Has Error' });
}
return payload || errorUtil.ERROR({ error: 'Your Token Verify Faild' });
}
async handle(ctx: Context, next: () => Promise): Promise {
const token = ctx.message.token;
if (token) {
Context.setAttr(TOKEN_DECODED, verify(token, await this.configProvider.get(JWT_SECRET_OR_PUBLIC_KEY, '123456')));
} else {
throw new JsonWebTokenError('Token is required.');
}
await next();
}
async requestJsonWebTokenAfterInfo(
@Req() req,
@Body() tokenDto: TokenDto,
): Promise {
try {
const validateTokenResult = await this.tokenService.validate(
tokenDto.token,
);
if (validateTokenResult) {
const jwtPayload: IJwtPayload = await this.tokenService.decode(
tokenDto.token,
);
const { user } = await this.authService.info({ id: jwtPayload.id });
return plainToClass(OutAccountDto, { user });
} else {
throw new JsonWebTokenError('invalid token');
}
} catch (error) {
throw error;
}
}
}
return new Promise((resolve, reject) => {
let dtk;
try {
dtk = jwt.decode(tk, {complete: true}) || {};
}
catch (err) {
return reject(new jwt.JsonWebTokenError('Cannot decode JWT token', err));
}
if (!dtk.header ||
dtk.header.alg !== 'RS256') {
return reject(new jwt.JsonWebTokenError('Algorithm must be RS256'));
}
return resolve(dtk);
});
}
jwt.verify(tk, key, (err, payload) => {
if (err) {
return reject(new jwt.JsonWebTokenError('Cannot verify token', err));
}
return resolve(payload);
});
});
async requestJsonWebTokenAfterInfo(@Req() req, @Body() tokenDto: TokenDto): Promise {
try {
const validateTokenResult = await this.tokenService.validate(tokenDto.token);
if (validateTokenResult) {
const jwtPayload: IJwtPayload = await this.tokenService.decode(tokenDto.token);
const { user } = await this.authService.info({ id: jwtPayload.id });
const token = await this.tokenService.create(user);
return plainToClass(UserTokenDto, { user, token });
} else {
throw new JsonWebTokenError('invalid token');
}
} catch (error) {
throw error;
}
}