I implemented authentication strategy basing on that article: https://docs.nestjs.com/techniques/authentication. But I would like to expand that JwtStrategy on checking roles. It would be easiest to just add checks for oles in jwt.strategy.ts
as there is already taken user basing on JWT payload.
But I don't know how to pass additional argument to validate
function.
What I would like to implement:
async validate(payload: JwtPayload, done: Function, role: string) {
const user = await this.authService.validateUser(payload);
if (!user || user.role !== role) {
return done(new UnauthorizedException(), false);
}
done(null, user);
}
but I don't know how I could pass additional role
argument to that function. I am using decorator @UseGuards(AuthGuard('jwt'))
for enabling guard. What I would like to achieve is add there as an additional parameter role
string and using it in JWTStrategy.
What is easiest way to implement that? Or do I need to implement two seperate guards?
EDIT: Actually I wasn't aware that AuthGuard automatically attach user to request. Solution was just simply implement RoleGuard from url pointed by @hdias2310. (https://docs.nestjs.com/guards)
A Passport strategy for authenticating with a JSON Web Token. This module lets you authenticate endpoints using a JSON web token. It is intended to be used to secure RESTful endpoints without sessions.
Passport is the most popular node.js authentication library, well-known by the community and successfully used in many production applications. It's straightforward to integrate this library with a Nest application using the @nestjs/passport module.
JSON Web Token and Passport can be primarily classified as "User Management and Authentication" tools. JSON Web Token and Passport are both open source tools. It seems that Passport with 15.9K GitHub stars and 936 forks on GitHub has more adoption than JSON Web Token with 2.59K GitHub stars and 259 GitHub forks.
You will need to have another guard to make a role verification.
You can get an example of implementation in NestJS docs (https://docs.nestjs.com/guards), in the "Role-based authentication" section.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With