I've a guard which returns false if the request doesn't have correct jwt token or has expired jwt token. But I'm not being able to send the message back to notify why the request is 403 forbidden.
here's my code
@Guard()
export class AuthGuard implements CanActivate {
canActivate(req: Request, context: ExecutionContext): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
if (req.headers.authorization && req.headers.authorization.toString().split(' ')[0] === 'Bearer') {
const token: string = req.headers.authorization.toString().split(' ')[1];
Database.Connection.then((connection: Connection) => {
const decoded = jwt.verify(token, 'secret');
connection.getRepository(User).findOneById(decoded.data).then((user: User) => {
(req as any).user = user;
resolve(true);
});
}).catch((err) => {
resolve(false);
});
} else {
resolve(false);
}
});
}
}
You could take a look at my repo's this is exactly the same problem and a use a middleware and a custom exception to handle and send back to the client
Hi @nmabhinandan,
It's easy. Instead of returning false
, just throw a HttpException
.
Also, it'd be easier to use async / await instead of resolve()
@kamilmysliwiec can canActivate be async?
@nmabhinandan of course! I see there's no example in the docs. Good point, maybe I should create one :slightly_smiling_face:
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
@nmabhinandan of course! I see there's no example in the docs. Good point, maybe I should create one :slightly_smiling_face: