0
0
NestJSframework~10 mins

JWT authentication guard in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - JWT authentication guard
Request comes in
Guard intercepts request
Extract JWT from header
Verify JWT validity
Allow access
Controller handles request
The guard checks the request for a JWT token, verifies it, and either allows or denies access based on validity.
Execution Sample
NestJS
canActivate(context: ExecutionContext) {
  const request = context.switchToHttp().getRequest();
  const token = this.extractToken(request);
  return this.jwtService.verifyAsync(token).then(() => true).catch(() => false);
}
This code checks if the JWT token in the request is valid and returns true or false accordingly.
Execution Table
StepActionInputResultNext Step
1Guard intercepts requestIncoming HTTP requestRequest object extractedExtract JWT token
2Extract JWT tokenRequest headersJWT token string or undefinedVerify JWT token
3Verify JWT tokenJWT token string or undefinedToken valid or invalidAllow or deny access
4Allow accessToken validReturn trueController handles request
5Deny accessToken invalid or missingReturn falseRequest denied with 401
💡 Execution stops after returning true or false to allow or deny access.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
requestundefinedHTTP request objectHTTP request objectHTTP request object
tokenundefinedJWT token string or undefinedJWT token string or undefinedJWT token string or undefined
verificationResultundefinedundefinedtrue or falsetrue or false
Key Moments - 3 Insights
What happens if the JWT token is missing from the request?
At Step 2 in the execution_table, if the token is undefined, the verification at Step 3 fails, leading to denial of access at Step 5.
Why does the guard return true or false instead of throwing an error?
The guard returns true or false to signal if access is allowed or denied. Returning false triggers NestJS to respond with 401 Unauthorized automatically, as shown in Step 5.
How does the guard extract the JWT token from the request?
At Step 2, the guard reads the Authorization header from the request and extracts the token part, usually after 'Bearer '. If missing, token is undefined.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result at Step 3 if the token is invalid?
AToken invalid
BToken valid
CToken missing
DToken expired
💡 Hint
Check Step 3 'Result' column in the execution_table for invalid token cases.
At which step does the guard decide to deny access?
AStep 3
BStep 5
CStep 4
DStep 2
💡 Hint
Look at the 'Next Step' and 'Action' columns in the execution_table for denial.
If the token is missing, what will the verificationResult variable be after Step 3?
Atrue
Bundefined
Cfalse
Dnull
💡 Hint
Refer to variable_tracker for verificationResult after Step 3 when token is missing.
Concept Snapshot
JWT Authentication Guard in NestJS:
- Intercepts incoming requests
- Extracts JWT token from Authorization header
- Verifies token validity asynchronously
- Returns true to allow access, false to deny
- Denied access triggers 401 Unauthorized response
Full Transcript
A JWT authentication guard in NestJS works by intercepting incoming HTTP requests. It extracts the JWT token from the Authorization header. Then it verifies the token asynchronously using the JWT service. If the token is valid, the guard returns true, allowing the request to proceed to the controller. If the token is missing or invalid, the guard returns false, which causes NestJS to respond with a 401 Unauthorized error. This process ensures only authenticated users can access protected routes.