Hey there,
I'm currently working on a scenario where I need to verify if the access token has expired and refresh it using the refresh token, all within the canActivate method of the AuthGuard. However, I've encountered an issue: if the access token expires and I make a call, it throws a 401 Unauthorized response from passport validation. Oddly, after this response, the cookies get set.
I'm wondering if there's a more efficient approach to managing the access token based on cookies. Any suggestions or insights would be greatly appreciated!
Thanks in advance!
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass()
]);
if (isPublic) {
return true;
}
const req = context.switchToHttp().getRequest();
const res = context.switchToHttp().getResponse();
try {
const { accessToken, refreshToken } = req.signedCookies;
if (accessToken) {
return this.activate(context);
}
const payload: JwtToken = this.tokenService.isTokenValid(refreshToken);
const existingToken = await this.tokenService.findOneByToken(payload);
if (!existingToken || !existingToken?.isValid) {
throw new HttpException('Authentication invalid', HttpStatus.UNAUTHORIZED);
}
this.tokenService.attachCookiesToResponse(res, payload.user, existingToken.refreshToken);
return this.activate(context);
} catch (err) {
throw new HttpException('Authentication invalid', HttpStatus.UNAUTHORIZED);
}
}```