Bird
0
0

How can you securely create a JWT token in FastAPI that includes user data and expiration, using the 'datetime' module?

hard🚀 Application Q9 of 15
FastAPI - Authentication and Security
How can you securely create a JWT token in FastAPI that includes user data and expiration, using the 'datetime' module?
ASet payload with 'sub' and 'exp' as current UTC time plus timedelta, then encode with secret and HS256
BSet payload with 'sub' only, then encode without expiration
CSet payload with 'exp' as string '1 hour', then encode with secret
DEncode payload with 'sub' and 'iat' as local time string
Step-by-Step Solution
Solution:
  1. Step 1: Use datetime for expiration

    Calculate expiration by adding timedelta to current UTC time, convert to timestamp for 'exp'.
  2. Step 2: Create payload and encode

    Include 'sub' and 'exp' in payload, then encode with secret and HS256 algorithm.
  3. Final Answer:

    Set payload with 'sub' and 'exp' as current UTC time plus timedelta, then encode with secret and HS256 -> Option A
  4. Quick Check:

    Use datetime + timedelta for 'exp' claim [OK]
Quick Trick: Use datetime.utcnow() + timedelta for 'exp' in payload [OK]
Common Mistakes:
MISTAKES
  • Using string for expiration
  • Omitting 'exp' claim
  • Using local time instead of UTC

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes