labd / django-cognito-jwt Goto Github PK
View Code? Open in Web Editor NEWAn Authentication backend for Django Rest Framework for AWS Cognito JWT tokens
License: MIT License
An Authentication backend for Django Rest Framework for AWS Cognito JWT tokens
License: MIT License
Softwares
Python: 3.6.8
Django: 2.2.2
OSX: 10.14.2
django-cognito-jwt: 0.0.3
According to #3 I have to customized my User
model. Neither single one of the works. I had tried both too.
COGNITO_USER_MODEL
COGNITO_USER_MODEL = "cognitos.User"
Result:
SystemCheckError: System check identified some issues:
ERRORS:
auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'.
HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'.
auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'.
HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'.
cognitos.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'.
HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'.
cognitos.User.is_superuser: (models.E006) The field 'is_superuser' clashes with the field 'is_superuser' from model 'cognitos.user'.
cognitos.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'.
HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'.
AUTH_USER_MODEL
AUTH_USER_MODEL = "cognitos.User"
Result:
SystemCheckError: System check identified some issues:
ERRORS:
cognitos.User.is_superuser: (models.E006) The field 'is_superuser' clashes with the field 'is_superuser' from model 'cognitos.user'.
COGNITO_USER_MODEL and AUTH_USER_MODEL
COGNITO_USER_MODEL = "cognitos.User"
AUTH_USER_MODEL = "cognitos.User"
SystemCheckError: System check identified some issues:
ERRORS:
cognitos.User.is_superuser: (models.E006) The field 'is_superuser' clashes with the field 'is_superuser' from model 'cognitos.user'.
What is the correct approach using this library?
In the backend.py JSONWebTokenAuthentication.authenticate() method, you call UserModel.objects.get_or_create_for_cognito() but this obviously is not a built-in method of the UserManager.
The documentation should include that this needs to be implemented and also provide guidance on how it needs to work. From what I can gather the Cognito APIs require an access token (which isn't part of your default method signature, which passes only the jwt_payload to get_or_create_from_cognito) to retrieve the user itself from Cognito but if I try to use the JWT token that was passed in, it fails validation with an error about needing a string not a byte string but even converting it back, it fails:
An error occurred (InvalidParameterException) when calling the GetUser operation: 1 validation error detected: Value at 'accessToken' failed to satisfy constraint: Member must satisfy regular expression pattern: [A-Za-z0-9-_=.]+
I think adding a sample implementation of this method would be extremely helpful.
I am getting the following error (Presumable after token is Expired):
WrappedAttributeError at /api/ module 'jwt' has no attribute 'ExpiredSignature'
The package was working perfectly for 2-3 months but this has started appearing recently.
I have the django-cognito-jwt integrated with DRF, but when I try to access the /admin interface, it shows me id/password login form.
How can I login on the django admin interface?
Thanks!
Hi, I try to use this repository in my project. Get an token error in JSONWebTokenAuthentication.authenticate of Django-cognito-jwt.
I am not sure if I write the right thing in setting.py
, it is the COGNITO_AUDIENCE
is the App client id of Cognito app (web)? Pls tell me how to find the right info, thanks.
COGNITO_PUBLIC_KEYS_CACHING_ENABLED and COGNITO_PUBLIC_KEYS_CACHING_TIMEOUT
Do you have any recommendation when I implement my website using AWS Lambda
?
Hi,
is it possible to make Cognito Audience setting as optional?
Trying to include this library in my Python 3.5 project yields compiler errors inside Pycharm:
Invalid syntax: Python 3.5 does not support 'f' format
@cached_property
def pool_url(self):
return f'https://cognito-idp.%s.amazonaws.com/%s' % (
self.aws_region, self.aws_user_pool)
hi we need to allow various requests from ui like mobile, website, etc, and i need to set multiple
COGNITO_AUDIENCE ='xxxxxxxxxxxxxxxxxxx'
in settings,
ImportError: Could not import 'django_cognito_jwt.JSONWebTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'RSAAlgorithm'.
Just started getting this a few days ago, wondering if anyone else has experienced the same thing?
I saw in another issue (#34) that an update to PyJWT was affecting this library and to downgrade it to 1.7.1, but that didn't work for me.
Could you add an example authentication flow to the README? That would be helpful, to see how this authentication works from the client.
See https://aws.amazon.com/blogs/aws/built-in-authentication-in-alb/
Now, when I navigate to an authenticated page my Fargate containers receive the originating request with the X-Amzn-Oidc-* headers set by ALB. Using the information in those headers (claims-data, identity, access-token) my application can implement authorization.
Hi,
Under normal load, the library works fine but when load increases I start to get below error
File "/usr/local/lib/python3.8/site-packages/django_cognito_jwt/validator.py", line 30, in _json_web_keys
response = requests.get(self.pool_url + "/.well-known/jwks.json")
File "/usr/local/lib/python3.8/site-packages/requests/api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "/usr/local/lib/python3.8/site-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python3.8/site-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.8/site-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.8/site-packages/requests/adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='cognito-idp.xx-xxxx.amazonaws.com', port=443): Max retries exceeded with url: /us-west-2_xxxxxxxxxx/.well-known/jwks.json (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f72c1d67400>: Failed to establish a new connection: [Errno -2] Name does not resolve'))
I propose to initialize the token_validator
just once in backend.py like below
class JSONWebTokenAuthentication(BaseAuthentication):
"""Token based authentication using the JSON Web Token standard."""
token_validator = None
def authenticate(self, request):
"""Entrypoint for Django Rest Framework"""
jwt_token = self.get_jwt_token(request)
if jwt_token is None:
return None
if not self.token_validator:
self.token_validator = self.get_token_validator(request)
# Authenticate token
try:
#token_validator = self.get_token_validator(request)
jwt_payload = self.token_validator.validate(jwt_token)
except TokenError as e:
raise exceptions.AuthenticationFailed()
This might be an easy question, but for me this is first time to customize the User
model. And I have followed #3 I think customized the User
model is mandatory by now. Then please support on best practice on this issue.
"GET /cognito HTTP/1.1" 301 0
Internal Server Error: /cognito/
Traceback (most recent call last):
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch
self.initial(request, *args, **kwargs)
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/rest_framework/views.py", line 400, in initial
self.perform_authentication(request)
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/rest_framework/views.py", line 326, in perform_authentication
request.user
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/rest_framework/request.py", line 223, in user
self._authenticate()
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/rest_framework/request.py", line 376, in _authenticate
user_auth_tuple = authenticator.authenticate(self)
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/django_cognito_jwt/backend.py", line 31, in authenticate
USER_MODEL = self.get_user_model()
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/django_cognito_jwt/backend.py", line 37, in get_user_model
return django_apps.get_model(user_model, require_ready=False)
File "/Users/sarit/.pyenv/versions/ht6m/lib/python3.6/site-packages/django/apps/registry.py", line 203, in get_model
app_label, model_name = app_label.split('.')
ValueError: too many values to unpack (expected 2)
See conda-forge/staged-recipes#11685 for details
Cognito access tokens are lacking the aud
field (cf https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html#amazon-cognito-user-pools-using-the-access-token) making their decoding impossible/invalid with this library since the audience is provided & expected at the decoding step: https://github.com/labd/django-cognito-jwt/blob/master/src/django_cognito_jwt/validator.py#L64.
Would you be willing to accept a PR making the audience optional ?
see ref for removal of these two util functions here https://docs.djangoproject.com/en/4.0/releases/4.0/#features-removed-in-4-0
see ref for smart_text replacement here https://docs.djangoproject.com/en/3.2/ref/utils/#django.utils.encoding.smart_text
I have no idea where I should ask, but at least experts here should shed the light for me
How can I use JSONWebTokenAuthentication
with GraphQL and also how to customized the permission class
?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.