Link Search Menu Expand Document

Broken JSON Web Token in Python

Play SecureFlag Play Python Labs on this vulnerability with SecureFlag!

Flask

To start using JSON Web Tokens (JWT) in a Flask application, you need to install and set up the “Flask-JWT-Extended” extension. Then add it to you applications configuration settings.

app = Flask(__name__)
app.config['JWT_SECRET_KEY'] = 'your_very_secret_key_here'

jwt = JWTManager(app)

FastAPI

Below is an example of a JWT set in FastAPI from a secret value set in the environment variables.

JWT_SUBJECT = "access"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7

def create_jwt_token(
    *,
    jwt_content: Dict[str, str],
    secret_key: str,
    expires_delta: timedelta,
) -> str:
    to_encode = jwt_content.copy()
    expire = datetime.utcnow() + expires_delta
    to_encode.update(JWTMeta(exp=expire, sub=JWT_SUBJECT).dict())
    return jwt.encode(to_encode, secret_key, algorithm=ALGORITHM)


def create_access_token_for_user(user: User, secret_key: str) -> str:
    return create_jwt_token(
        jwt_content=JWTUser(username=user.username).dict(),
        secret_key=secret_key,
        expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES),
    )

...

token = jwt.create_access_token_for_user(
    user,
    str(settings.secret_key.get_secret_value()),
)

Django

In Django, JWT management isn’t provided out of the box but can be implemented using libraries such as “djangorestframework-simplejwt” or “django-rest-framework-jwt.” These libraries handle JWT creation, distribution, and validation, thus integrating JWT into Django’s authentication framework.

These add-ons have simple management for you where you can provide the secret key in settings.py

SECRET_KEY = "secret_key_value"