djangorestframework-simplejwt icon indicating copy to clipboard operation
djangorestframework-simplejwt copied to clipboard

How setup AWS Cognito with djangorestframework-simplejwt

Open mateuspadua opened this issue 11 months ago • 2 comments

I've been trying setup AWS Cognito using JWK_URL, but not working. Is there a way to do this?

My settings.py

SIMPLE_JWT = {
    "JWK_URL": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_XXXXXXX/.well-known/jwks.json",
    "ALGORITHM": "RS256",
    "AUDIENCE": "<my cognito app client>",
    "ISSUER": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_XXXXXXX",
}

myview.py


from rest_framework_simplejwt.authentication import JWTAuthentication

class TesteViewSet(
    mixins.ListModelMixin,
    viewsets.GenericViewSet,
):
    queryset = MyModel.objects.all()
    serializer_class = TesteSerializer
    authentication_classes = [JWTAuthentication]

What more I need to do?

Tks in advance, :)

mateuspadua avatar Mar 18 '24 11:03 mateuspadua

Unfortunately, I'm not really familiar with AWS Cognito. Posting what you did in the end would be helpful:)

Andrew-Chen-Wang avatar Mar 19 '24 07:03 Andrew-Chen-Wang

Hi guys, I was hit by same problem, but found some solution.

This is the SIMPLE_JWT settings I used:

SIMPLE_JWT = {
    'ALGORITHM': 'RS256',
    'USER_ID_CLAIM': 'username',
    'USER_ID_FIELD': '<your-user-username-field>',
    'TOKEN_TYPE_CLAIM': 'token_use',
    'ISSUER': 'https://cognito-idp.<aws-region>.amazonaws.com/<user-pool-id>',
    'JWK_URL':'https://cognito-idp.<aws-region>.amazonaws.com/<user-pool-id>/.well-known/jwks.json',
}

Pay special attention to those details please:

  • There is no AUDIENCE key in my SIMPLE_JWT, because if you define it, rest_framework_simplejwt package made validation against JWT payload['aud'] and fail, since it is not set by Cognito.
  • You need to tell which JWT payload attribute contain user identifier, thats USER_ID_CLAIM in my case (can be also "sub")
  • You need to describe, how rest_framework_simplejwt find relevant record in DB and define attribute, where you have stored value from USER_ID_CLAIM payload; thats the USER_ID_FIELD

Hope it helps 🙏

msgre avatar Jul 11 '24 12:07 msgre