Files
What you'll learn
- Explain what a JWT is (a signed, readable, expiring claim about who is asking) and why the server can trust one it did not store
- Register JwtModule for the whole app and sign a payload with JwtService.signAsync
- Write a guard that reads a bearer token, verifies it, puts the payload on the request and answers 401 for anything else, and bind it with APP_GUARD
- Open individual routes with a @Public() decorator the guard reads through Reflector
Press Run tests to start the app. Its log appears here.Graded endpoints
Listing the shelter is public, so the guard lets it through with no Authorization header
Changing the roster is not public; the guard answers Nest's 401 before the handler runs
The right password earns a token; its first segment is the base64url JWT header, the same for every HS256 token. The token is kept for the requests below
The password does not match, so UnauthorizedException, and no hint about which half was wrong
No such user: the same 401, the same body
The guard verified the bearer token and put its payload on request.user; iat and exp were added by the signer
Three segments, but a signature the secret never produced: verifyAsync throws and the guard answers 401
A valid token sent as Basic instead of Bearer is not a bearer token; the header's scheme is part of the contract
No Authorization header at all
Signed in, john may add a cat
Reading a cat is public too
Deleting is staff only
Signed in, john may remove a cat
Tom is gone