mirror of
https://github.com/fastapi-users/fastapi-users.git
synced 2025-08-26 04:25:46 +08:00
Enable RS256/ES256 and other algorithms for JWT strategy (#943)
* Implement RS256 for JWT auth * Update docs with RS256 example * Added ES256 tests * Format with isort and black * Removed example RSA key pair (so as not to tempt people to use it) * Added pyjwt[crypto] to requirements * Removed pycryptodome by hardcoding example keys * Removed unnecessary Tuple import from typing
This commit is contained in:
@ -18,10 +18,22 @@ class JWTStrategy(Strategy, Generic[models.UC, models.UD]):
|
||||
secret: SecretType,
|
||||
lifetime_seconds: Optional[int],
|
||||
token_audience: List[str] = ["fastapi-users:auth"],
|
||||
algorithm: str = "HS256",
|
||||
public_key: Optional[SecretType] = None,
|
||||
):
|
||||
self.secret = secret
|
||||
self.lifetime_seconds = lifetime_seconds
|
||||
self.token_audience = token_audience
|
||||
self.algorithm = algorithm
|
||||
self.public_key = public_key
|
||||
|
||||
@property
|
||||
def encode_key(self) -> SecretType:
|
||||
return self.secret
|
||||
|
||||
@property
|
||||
def decode_key(self) -> SecretType:
|
||||
return self.public_key or self.secret
|
||||
|
||||
async def read_token(
|
||||
self, token: Optional[str], user_manager: BaseUserManager[models.UC, models.UD]
|
||||
@ -30,7 +42,9 @@ class JWTStrategy(Strategy, Generic[models.UC, models.UD]):
|
||||
return None
|
||||
|
||||
try:
|
||||
data = decode_jwt(token, self.secret, self.token_audience)
|
||||
data = decode_jwt(
|
||||
token, self.decode_key, self.token_audience, algorithms=[self.algorithm]
|
||||
)
|
||||
user_id = data.get("user_id")
|
||||
if user_id is None:
|
||||
return None
|
||||
@ -47,7 +61,9 @@ class JWTStrategy(Strategy, Generic[models.UC, models.UD]):
|
||||
|
||||
async def write_token(self, user: models.UD) -> str:
|
||||
data = {"user_id": str(user.id), "aud": self.token_audience}
|
||||
return generate_jwt(data, self.secret, self.lifetime_seconds)
|
||||
return generate_jwt(
|
||||
data, self.encode_key, self.lifetime_seconds, algorithm=self.algorithm
|
||||
)
|
||||
|
||||
async def destroy_token(self, token: str, user: models.UD) -> None:
|
||||
raise StrategyDestroyNotSupportedError(
|
||||
|
Reference in New Issue
Block a user