Bird
0
0

In a NestJS app using session-based authentication, which is the most effective way to ensure that only authenticated users can access a protected route?

hard📝 Conceptual Q8 of 15
NestJS - Authentication
In a NestJS app using session-based authentication, which is the most effective way to ensure that only authenticated users can access a protected route?
ACreate a custom guard that checks if <code>request.session.user</code> exists before allowing access
BCheck for a JWT token in the request headers inside the controller method
CUse a middleware that always redirects to login regardless of session state
DAllow access and rely on client-side checks to hide protected content
Step-by-Step Solution
Solution:
  1. Step 1: Understand session-based auth protection

    Access control should verify the session data server-side before granting access.
  2. Step 2: Evaluate options

    Create a custom guard that checks if request.session.user exists before allowing access uses a guard to check request.session.user, which is the correct server-side approach.
  3. Step 3: Why other options are incorrect

    Check for a JWT token in the request headers inside the controller method uses JWT which is unrelated to session-based auth; C redirects unconditionally; D relies on insecure client-side checks.
  4. Final Answer:

    Create a custom guard that checks if request.session.user exists before allowing access -> Option A
  5. Quick Check:

    Server-side guard validates session user [OK]
Quick Trick: Use guards to check session user server-side [OK]
Common Mistakes:
  • Mixing JWT with session-based auth
  • Relying on client-side validation only
  • Using middleware that doesn't conditionally check session

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes