Reputation: 470
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)
Upvotes: 12
Views: 16323
Reputation: 840
To add to the accepted answer, I would like to point to auth0.com that has a good section about roles based authentication.
Upvotes: 0
Reputation: 326
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.
Upvotes: 18