Skip to content
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

Make token validation compatible with AccessToken where "aud" claim is not provided #33

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
20 changes: 13 additions & 7 deletions src/django_cognito_jwt/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,20 @@ def validate(self, token):
if not public_key:
raise TokenError("No key found for this token")

params = {
"jwt": token,
"key": public_key,
"issuer": self.pool_url,
"algorithms": ["RS256"]
}

# include audience validation if "aud" claim is provided in token payload
token_payload = jwt.decode(token, verify=False)
if "aud" in token_payload:
params.update({"audience": self.audience})

try:
jwt_data = jwt.decode(
token,
public_key,
audience=self.audience,
issuer=self.pool_url,
algorithms=["RS256"],
)
jwt_data = jwt.decode(**params)
except (jwt.InvalidTokenError, jwt.ExpiredSignature, jwt.DecodeError) as exc:
raise TokenError(str(exc))
return jwt_data
13 changes: 13 additions & 0 deletions tests/test_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,19 @@ def test_validate_token_error_aud(cognito_well_known_keys, jwk_private_key_one):
auth.validate(token)


def test_validate_token_missing_aud(cognito_well_known_keys, jwk_private_key_one):
token = create_jwt_token(
jwk_private_key_one,
{
"iss": "https://cognito-idp.eu-central-1.amazonaws.com/bla",
# missing aud
"sub": "username",
},
)
auth = validator.TokenValidator("eu-central-1", "bla", "my-audience")
auth.validate(token)


@pytest.mark.parametrize(
"is_cache_enabled,responses_calls", [(None, 2), (False, 2), (True, 1)]
)
Expand Down