Skip to content

Commit 594fb07

Browse files
authored
fix(jwt): store raw JWT token in cookies without Bearer prefix (#4552)
* fix(jwt): store raw JWT token in cookies without Bearer prefix * fix(jwt): update OAuth2PasswordBearerAuth as well * fix(jwt): restore backwards compatibility * test(jwt): add assertion for correct cookie format * fix(jwt): parse correct and legacy token formats * docs: restore pydoc string
1 parent 971ee79 commit 594fb07

File tree

3 files changed

+13
-5
lines changed

3 files changed

+13
-5
lines changed

litestar/security/jwt/auth.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -546,7 +546,7 @@ def login(
546546
key=self.key,
547547
path=self.path,
548548
httponly=True,
549-
value=self.format_auth_header(encoded_token),
549+
value=encoded_token,
550550
max_age=int((token_expiration or self.default_token_expiration).total_seconds()),
551551
secure=self.secure,
552552
samesite=self.samesite,
@@ -799,7 +799,7 @@ def login(
799799
key=self.key,
800800
path=self.path,
801801
httponly=True,
802-
value=self.format_auth_header(encoded_token),
802+
value=encoded_token,
803803
max_age=expires_in,
804804
secure=self.secure,
805805
samesite=self.samesite,

litestar/security/jwt/middleware.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -262,8 +262,10 @@ async def authenticate_request(self, connection: ASGIConnection[Any, Any, Any, A
262262
Returns:
263263
AuthenticationResult
264264
"""
265-
auth_header = connection.headers.get(self.auth_header) or connection.cookies.get(self.auth_cookie_key)
266-
if not auth_header:
265+
encoded_token = (
266+
connection.headers.get(self.auth_header, "").partition(" ")[-1]
267+
or connection.cookies.get(self.auth_cookie_key, "").split(" ")[-1]
268+
)
269+
if not encoded_token:
267270
raise NotAuthorizedException("No JWT token found in request header or cookies")
268-
encoded_token = auth_header.partition(" ")[-1]
269271
return await self.authenticate_token(encoded_token=encoded_token, connection=connection)

tests/unit/test_security/test_jwt/test_auth.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,12 @@ def logout_handler(request: Request["User", Token, Any]) -> dict[str, str]:
357357
client.cookies = {auth_cookie: jwt_auth.format_auth_header(encoded_token)}
358358
response = client.get("/my-endpoint")
359359
assert response.status_code == HTTP_200_OK
360+
361+
client.cookies.clear()
362+
client.cookies = {auth_cookie: encoded_token}
363+
response = client.get("/my-endpoint")
364+
assert response.status_code == HTTP_200_OK
365+
360366
response = client.get("/logout")
361367
if decoded_token.jti:
362368
assert response.json()["message"] == "logged out successfully"

0 commit comments

Comments
 (0)