/ examples / jwt_auth / jwt_auth.py
jwt_auth.py
 1  """Sample JWT authentication module for testing purposes.
 2  
 3  NOT SUITABLE FOR PRODUCTION USE.
 4  """
 5  
 6  import logging
 7  
 8  import jwt
 9  from flask import Response, make_response, request
10  from werkzeug.datastructures import Authorization
11  
12  BEARER_PREFIX = "bearer "
13  
14  _logger = logging.getLogger(__name__)
15  
16  
17  def authenticate_request() -> Authorization | Response:
18      _logger.debug("Getting token")
19      error_response = make_response()
20      error_response.status_code = 401
21      error_response.set_data(
22          "You are not authenticated. Please provide a valid JWT Bearer token with the request."
23      )
24      error_response.headers["WWW-Authenticate"] = 'Bearer error="invalid_token"'
25  
26      token = request.headers.get("Authorization")
27      if token is not None and token.lower().startswith(BEARER_PREFIX):
28          token = token[len(BEARER_PREFIX) :]  # Remove prefix
29          try:
30              # NOTE:
31              # - This is a sample implementation for testing purposes only.
32              # - Here we're using a hardcoded key, which is not secure.
33              # - We also aren't validating that the user exists.
34              token_info = jwt.decode(token, "secret", algorithms=["HS256"])
35              if not token_info:  # pragma: no cover
36                  _logger.warning("No token_info returned")
37                  return error_response
38  
39              return Authorization(auth_type="jwt", data=token_info)
40          except jwt.exceptions.InvalidTokenError:
41              pass
42  
43      _logger.warning("Missing or invalid authorization token")
44      return error_response