Skip to content

Support custom auth header and user_or_create_function #5

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 2 commits 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
13 changes: 11 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ Add the following lines to your Django settings.py file:

COGNITO_AWS_REGION = '<aws region>' # 'eu-central-1'
   COGNITO_USER_POOL = '<user pool>' # 'eu-central-1_xYzaq'
   COGNITO_AUDIENCE = '<client id>'
   COGNITO_AUDIENCE = '<client id>' # the App Client Id in your AWS Cognito console
COGNITO_GET_USER_OR_CREATE_FUNCTION = 'USER_MODEL.get_or_create_for_cognito' # your custom get user function name, it will create a new user if it does not exist
COGNITO_AUTH_HEADER = 'bearer' # your custom token header, like 'bearer xxxx.xxxxxxxx.xxxx'

Also update the rest framework settings to use the correct authentication backend:

Expand All @@ -45,4 +47,11 @@ Also update the rest framework settings to use the correct authentication backen
...
],
...
}
}

And for your application send the request, just set the request header's Authorization property as this:

.. code-block:: python
"bearer xxxx.xxxxxxxx.xxxx"

The `bearer` is what you set in setting.py COGNITO_AUTH_HEADER.
7 changes: 5 additions & 2 deletions src/django_cognito_jwt/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,15 @@ def authenticate(self, request):
except TokenError:
raise exceptions.AuthenticationFailed()

user = USER_MODEL.objects.get_or_create_for_cognito(jwt_payload)
get_or_create_for_cognito_code = '{function_name}(jwt_payload, request)'.format(
function_name=settings.COGNITO_GET_USER_OR_CREATE_FUNCTION, jwt_payload=jwt_payload, request=request)

user = eval(get_or_create_for_cognito_code)
return (user, jwt_token)

def get_jwt_token(self, request):
auth = get_authorization_header(request).split()
if not auth or smart_text(auth[0].lower()) != 'bearer':
if not auth or smart_text(auth[0].lower()) != settings.COGNITO_AUTH_HEADER:
return None

if len(auth) == 1:
Expand Down