Skip to content

Commit d2c961a

Browse files
committed
Add option to decode access token
1 parent 9d7ca0b commit d2c961a

File tree

4 files changed

+23
-8
lines changed

4 files changed

+23
-8
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
.cache
88
.python-version
99
.venv
10+
venv/
1011
.idea/
1112

1213
/build/
@@ -17,3 +18,4 @@
1718

1819
# Editors
1920
.idea/
21+
.vscode/

README.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,7 @@ you can use the ``COGNITO_USER_MODEL`` setting.
7272
.. code-block:: python
7373
7474
COGNITO_USER_MODEL = "myproject.AppUser"
75+
76+
The library by default uses id token. To use access token, add the following lines to your Django ``settings.py`` file:
77+
.. {'id', 'access'} Default: 'id'
78+
COGNITO_TOKEN_TYPE = 'access'

src/django_cognito_jwt/backend.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ def get_token_validator(self, request):
5858
settings.COGNITO_AWS_REGION,
5959
settings.COGNITO_USER_POOL,
6060
settings.COGNITO_AUDIENCE,
61+
settings.COGNITO_TOKEN_TYPE,
6162
)
6263

6364
def authenticate_header(self, request):

src/django_cognito_jwt/validator.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import json
2+
from typing import Literal
23

34
import jwt
45
import requests
@@ -13,10 +14,14 @@ class TokenError(Exception):
1314

1415

1516
class TokenValidator:
16-
def __init__(self, aws_region, aws_user_pool, audience):
17+
def __init__(self, aws_region, aws_user_pool, audience, token_type: Literal["id", "access"] = "id"):
1718
self.aws_region = aws_region
1819
self.aws_user_pool = aws_user_pool
1920
self.audience = audience
21+
self.token_type = token_type
22+
23+
if token_type not in ["id", "access"]:
24+
raise TokenError("Invalid token type. Choose either id or access token.")
2025

2126
@cached_property
2227
def pool_url(self):
@@ -58,13 +63,16 @@ def validate(self, token):
5863
raise TokenError("No key found for this token")
5964

6065
try:
61-
jwt_data = jwt.decode(
62-
token,
63-
public_key,
64-
audience=self.audience,
65-
issuer=self.pool_url,
66-
algorithms=["RS256"],
67-
)
66+
params = {
67+
"jwt": token,
68+
"key": public_key,
69+
"issuer": self.pool_url,
70+
"algorithms": ["RS256"]
71+
}
72+
if self.token_type == "id":
73+
params.update({"audience": self.audience})
74+
75+
jwt_data = jwt.decode(**params)
6876
except (
6977
jwt.InvalidTokenError,
7078
jwt.ExpiredSignatureError,

0 commit comments

Comments
 (0)