Skip to content

Commit

Permalink
Merge pull request #93 from pythrick/fix-decode_base64
Browse files Browse the repository at this point in the history
Fix JSONDecodeError due to Improper Handling of Nested JSON Strings in JWT Payloads
  • Loading branch information
Colin-b authored Jan 7, 2025
2 parents 9a5bf50 + ad3c68a commit 59d97fa
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Fixed
- Fix `JSONDecodeError` due to Improper Handling of Nested JSON Strings in JWT Payloads

### Changed
- Requires [`httpx`](https://www.python-httpx.org)==0.28.\*

Expand Down
2 changes: 1 addition & 1 deletion httpx_auth/_oauth2/tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def decode_base64(base64_encoded_string: str) -> str:
missing_padding = len(base64_encoded_string) % 4
if missing_padding != 0:
base64_encoded_string += "=" * (4 - missing_padding)
return base64.b64decode(base64_encoded_string).decode("unicode_escape")
return base64.urlsafe_b64decode(base64_encoded_string).decode("utf-8")


def is_expired(expiry: float, early_expiry: float) -> bool:
Expand Down
Empty file added tests/oauth2/tokens/__init__.py
Empty file.
30 changes: 30 additions & 0 deletions tests/oauth2/tokens/test_tokens.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import json
import jwt

from httpx_auth._oauth2.tokens import decode_base64


def test_decode_base64():
# Encode a JSON inside the JWT
dummy_token = jwt.encode({"name": "John"}, key="")
header, body, signature = dummy_token.split(".")

# Decode the body
decoded_bytes = decode_base64(body)

# Attempt to load JSON
result = json.loads(decoded_bytes)
assert result == {"name": "John"}


def test_decode_base64_with_nested_json_string():
# Encode a JSON inside the JWT
dummy_token = jwt.encode({"data": json.dumps({"something": ["else"]})}, key="")
header, body, signature = dummy_token.split(".")

# Decode the body
decoded_bytes = decode_base64(body)

# Attempt to load JSON
result = json.loads(decoded_bytes)
assert result == {"data": '{"something": ["else"]}'}

0 comments on commit 59d97fa

Please sign in to comment.