PyJWT's encode has a default algorithm='HS256', so it is not strictly required.
Step 2: Analyze the code snippet
The code calls encode with payload and secret; algorithm defaults to HS256, so it runs correctly and produces a token.
Final Answer:
No error; code runs correctly -> Option B
Quick Check:
Algorithm defaults to HS256 = no error [OK]
Hint: PyJWT encode defaults to HS256 algorithm [OK]
Common Mistakes:
Assuming algorithm defaults to HS256
Thinking payload must be string
Believing secret must be bytes
5. You want to create a JWT token in FastAPI that expires in 30 minutes. Which code snippet correctly adds the expiration time to the payload before encoding?
hard
A. payload = {"user_id": 1, "exp": datetime.utcnow() + timedelta(minutes=30)}
B. payload = {"user_id": 1, "exp": str(datetime.utcnow() + timedelta(minutes=30))}
C. payload = {"user_id": 1, "exp": time.time() + 1800}
D. payload = {"user_id": 1, "exp": datetime.now() + timedelta(minutes=30)}
Solution
Step 1: Understand JWT expiration format
The 'exp' claim must be a UTC datetime or a timestamp representing expiration time.
Step 2: Evaluate each option
payload = {"user_id": 1, "exp": datetime.utcnow() + timedelta(minutes=30)} uses datetime.utcnow() + timedelta for 30 minutes, which is correct. payload = {"user_id": 1, "exp": str(datetime.utcnow() + timedelta(minutes=30))} converts datetime to string, which is invalid. payload = {"user_id": 1, "exp": time.time() + 1800} uses time.time() but JWT expects datetime or timestamp as int, so this may cause issues. payload = {"user_id": 1, "exp": datetime.now() + timedelta(minutes=30)} uses datetime.now() which is local time, not UTC, causing potential errors.