Hello, I have a little problem with my RoleGuard, as in title the user object is undefined when I use my @Roles() decorator, but it does exist in the query above (me), I saw it is a common problem but noone made a clear answer how to fix it. The case when that JwtAuthGuard passed before Roles()were when I declared my JwtAuthGuard as a global guard in app.module.ts in providers just like RoleGuard { provide: APP_GUARD, useClass: JwtAuthGuard }, but I want some of my queries/mutations to be public for not-logged-in users. I spotted that JwtAuthGuard doesn't even run for now, because when I send request without authorization header it doesn't say Unauthenticated but Cannot read properties of undefined (reading 'role') from RoleGuard
#req.user is undefined in RoleGuard
1 messages · Page 1 of 1 (latest)
If you bind RoleGuard as global via the APP_GUARD and it reads from req.user, then however you populate req.user (like via the JwtAuthGuard) also needs to be global and running before the RoleGuard. To allow for some public routes, you can create metadata that is read during the route's evaluation and skip the guards as necessary. The docs show a primitive approach for this.
https://docs.nestjs.com/security/authentication#enable-authentication-globally
okay so if I didn't want to declare my RoleGuard globally I should remove that and use RoleGuard as
@UseGuards(RoleGuard)
@Roles(Role.ADMIN)
Yes, and anywhere you use RoleGuard you should also use the JwtAuthGuard before it
oh okay, so thats how it works, thank you so much, closing