Getting User Data by using Guards (Roles, JWT)
You can attach multiple guards together (@UseGuards(AuthGuard('jwt'), RolesGuard)) to pass the context between them. Then you will have access 'req.user' object inside 'RolesGuard'.
Additionally to your RolesGuard
you need to use an AuthGuard
.
Standard
You can use the standard AuthGuard
implementation which attaches the user object to the request. It throws a 401 error, when the user is unauthenticated.
@UseGuards(AuthGuard('jwt'))
Extension
If you need to write your own guard because you need different behavior, extend the original AuthGuard
and override the methods you need to change (handleRequest
in the example):
@Injectable()
export class MyAuthGuard extends AuthGuard('jwt') {
handleRequest(err, user, info: Error) {
// don't throw 401 error when unauthenticated
return user;
}
}
Why do this?
If you look at the source code of the AuthGuard
you can see that it attaches the user to the request as a callback to the passport method. If you don't want to use/extend the AuthGuard
, you will have to implement/copy the relevant parts.
const user = await passportFn(
type || this.options.defaultStrategy,
options,
// This is the callback passed to passport. handleRequest returns the user.
(err, info, user) => this.handleRequest(err, info, user)
);
// Then the user object is attached to the request
// under the default property 'user' which you can change by configuration.
request[options.property || defaultOptions.property] = user;