Skip to content

Support standard JWT payload #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 19 additions & 12 deletions fastapi_jwt/jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,9 @@ def utcnow():
]


class JwtAuthorizationCredentials:
def __init__(self, subject: Dict[str, Any], jti: Optional[str] = None):
self.subject = subject
self.jti = jti

def __getitem__(self, item: str) -> Any:
return self.subject[item]

class JwtAuthorizationCredentials(dict):
def __init__(self, payload: Dict[str, Any]):
super().__init__(payload)

class JwtAuthBase(ABC):
class JwtAccessCookie(APIKeyCookie):
Expand Down Expand Up @@ -75,6 +70,8 @@ def __init__(
algorithm: str = jwt.ALGORITHMS.HS256, # type: ignore[attr-defined]
access_expires_delta: Optional[timedelta] = None,
refresh_expires_delta: Optional[timedelta] = None,
decode_kwargs: Optional[dict] = None,
subject_key: Optional[str] = "sub"
):
assert jwt is not None, "python-jose must be installed to use JwtAuth"
if places:
Expand All @@ -93,6 +90,8 @@ def __init__(
self.algorithm = algorithm
self.access_expires_delta = access_expires_delta or timedelta(minutes=15)
self.refresh_expires_delta = refresh_expires_delta or timedelta(days=31)
self.decode_kwargs = decode_kwargs
self.subject_key = subject_key

@classmethod
def from_other(
Expand All @@ -103,13 +102,17 @@ def from_other(
algorithm: Optional[str] = None,
access_expires_delta: Optional[timedelta] = None,
refresh_expires_delta: Optional[timedelta] = None,
decode_kwargs: Optional[dict] = None,
subject_key: Optional[str] = "sub"
) -> 'JwtAuthBase':
return cls(
secret_key=secret_key or other.secret_key,
auto_error=auto_error or other.auto_error,
algorithm=algorithm or other.algorithm,
access_expires_delta=access_expires_delta or other.access_expires_delta,
refresh_expires_delta=refresh_expires_delta or other.refresh_expires_delta,
decode_kwargs=decode_kwargs or other.decode_kwargs,
subject_key=subject_key or other.subject_key
)

def _decode(self, token: str) -> Optional[Dict[str, Any]]:
Expand All @@ -119,6 +122,7 @@ def _decode(self, token: str) -> Optional[Dict[str, Any]]:
self.secret_key,
algorithms=[self.algorithm],
options={"leeway": 10},
**self.decode_kwargs
)
return payload
except jwt.ExpiredSignatureError as e: # type: ignore[attr-defined]
Expand Down Expand Up @@ -146,7 +150,7 @@ def _generate_payload(
now = utcnow()

return {
"subject": subject.copy(), # main subject
self.subject_key: subject.copy(), # main subject
"type": token_type, # 'access' or 'refresh' token
"exp": now + expires_delta, # expire time
"iat": now, # creation time
Expand Down Expand Up @@ -264,6 +268,7 @@ def __init__(
algorithm: str = jwt.ALGORITHMS.HS256, # type: ignore[attr-defined]
access_expires_delta: Optional[timedelta] = None,
refresh_expires_delta: Optional[timedelta] = None,
subject_key: Optional[str] = "sub"
):
super().__init__(
secret_key,
Expand All @@ -283,7 +288,7 @@ async def _get_credentials(

if payload:
return JwtAuthorizationCredentials(
payload["subject"], payload.get("jti", None)
payload
)
return None

Expand All @@ -296,15 +301,17 @@ def __init__(
algorithm: str = jwt.ALGORITHMS.HS256, # type: ignore[attr-defined]
access_expires_delta: Optional[timedelta] = None,
refresh_expires_delta: Optional[timedelta] = None,
decode_kwargs: Optional[dict] = None
):
super().__init__(
secret_key=secret_key,
places={"header"},
auto_error=auto_error,
algorithm=algorithm,
access_expires_delta=access_expires_delta,
refresh_expires_delta=refresh_expires_delta,
refresh_expires_delta=refresh_expires_delta
)
self.decode_kwargs = decode_kwargs

async def __call__(
self, bearer: JwtAuthBase.JwtAccessBearer = Security(JwtAccess._bearer)
Expand Down Expand Up @@ -405,7 +412,7 @@ async def _get_credentials(
return None

return JwtAuthorizationCredentials(
payload["subject"], payload.get("jti", None)
payload[self.subject_key], payload.get("jti", None)
)


Expand Down