AskReference
ProcessIntermediate

How does the create_access_token function in service/user.py generate a JWT token, and what is the default expiration time if none is provided?

The create_access_token function copies the input data, sets a default expiration of 15 minutes when no expires value is provided, and adds an 'exp' claim equal to the current UTC time plus that expiration. It then encodes the payload using the HS256 algorithm with SECRET_KEY and returns the resulting JWT string.

In service/user.py, create_access_token starts by making a shallow copy of the input data dictionary so the original is not modified. It records the current UTC time as 'now'. If the expires parameter is None, it sets expires to timedelta(minutes=15); otherwise it uses the supplied timedelta. The function then updates the copied dictionary to include an 'exp' key whose value is now plus the expiration time. Finally, it calls jwt.encode with this payload, using SECRET_KEY and the HS256 algorithm, and returns the encoded JWT. This means the default token lifetime is 15 minutes when no explicit expiration is passed to the function.

Key points

  • Copies the input data dict to avoid mutating the caller's dict.
  • Uses datetime.utcnow() as the base time for the token.
  • Defaults to a 15-minute expiration if no expires timedelta is supplied.
  • Sets the exp claim to now plus the expiration time.
  • Encodes the token with jwt.encode using the HS256 algorithm and SECRET_KEY.
Source:FastAPI: Modern Python Web Development· Authentication and Authorization· p. 167–177

Related questions

Cover of FastAPI: Modern Python Web Development

FastAPI: Modern Python Web Development

Bill Lubanovic;

First Edition · O'Reilly Media, Inc.

View this ebook