Skip to content

JWT sessions accept asymmetric algorithms that the built-in serializer cannot use #86

Description

@allen0099

Problem

SessionConfig.jwt_algorithm accepts RS*, ES*, PS* and EdDSA (JWT_ALGORITHMS in fastapi_cachex/session/config.py). However, JWTTokenSerializer signs and verifies every token with the single secret_key string (token_serializers.py, self._secret = config.secret_key.get_secret_value()).

For an asymmetric algorithm, PyJWT needs a private key to encode and a public key to decode, so a string secret fails:

>>> jwt.encode({"a": 1}, "x" * 40, algorithm="RS256")
jwt.exceptions.InvalidKeyError: Could not parse the provided public key.

The configuration is accepted at startup, but the first create_session() fails at runtime.

Options

  1. Validate early: restrict jwt_algorithm to HS256/HS384/HS512 unless a custom token_serializer is supplied. Alternatively, raise a clear configuration error when an asymmetric algorithm is combined with the built-in serializer. Rejecting values the config accepts today would be a breaking change.
  2. Support asymmetric keys: add jwt_private_key / jwt_public_key settings (PEM, SecretStr for the private key). The built-in serializer would encode with the private key and decode with the public one, so services that only verify tokens can hold just the public key.

Option 1 is the minimum fix. Option 2 makes the accepted values actually work.

Current documentation

docs/JWT_CLAIMS.md (since #85) notes that only the HS algorithms work out of the box, and that asymmetric algorithms need a custom serializer.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingsessionSession management subsystem

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions