Files
What you'll learn
- Separate authentication (who) from authorization (what they may do), and answer 401 for the first and 403 for the second
- Carry roles as a claim in the token and read them from request.user in a guard
- Write a guard that reads required roles from handler and class metadata through Reflector and lets undecorated routes through
- Order global guards so the one that needs a user runs after the one that finds it
Press Run tests to start the app. Its log appears here.Graded endpoints
New staff start as users
The seeded account holds the admin role
Her token carries the roles she was registered with
The roles claim travelled inside the token and came back out of verifyAsync
Signed in, so past AuthGuard; not an admin, so RolesGuard returns false and Nest answers its default 403
No token is 401, not 403: authentication is checked first, and a stranger is not told what an admin could do
The admin role is in his token, and the route asks for it
Reading one cat stays public
A route with no @Roles() is open to any signed-in member of staff; the guard returns true before looking at the user
Any staff, admin included
Deleting is admin only
The admin may
Public routes stay public: AuthGuard lets them through and RolesGuard finds no required roles