pip install django-warrant
-
In your Django project settings file, add the dotted path of
CognitoBackend
to your list ofAUTHENTICATION_BACKENDS
. Keep in mind that Django will attempt to authenticate a user using each backend listed, in the order listed until successful.AUTHENTICATION_BACKENDS = [ 'django_warrant.backend.CognitoBackend', ... ]
-
Set
COGNITO_USER_POOL_ID
andCOGNITO_APP_ID
in your settings file as well. Your User Pool ID can be found in the Pool Details tab in the AWS console. Your App ID is found in the Apps tab, listed as "App client id". -
Set
COGNITO_ATTR_MAPPING
in your settings file to a dictionary mapping a Cognito attribute name to a Django User attribute name. If your Cognito User Pool has any custom attributes, it is automatically prefixed withcustom:
. Therefore, you will want to add a mapping to your mapping dictionary as such{'custom:custom_attr': 'custom_attr'}
. Defaults to:{ 'email': 'email', 'given_name': 'first_name', 'family_name': 'last_name', }
-
Optional - Set
COGNITO_CREATE_UNKNOWN_USERS
toTrue
orFalse
, depending on if you wish local Django users to be created upon successful login. If set toFalse
, only existing local Django users are updated. Defaults toTrue
. -
Optional - Set
AWS_ACCESS_KEY_ID
andAWS_SECRET_ACCESS_KEY
to the AWS access keys you would like to use. Defaults toNone
, which will use the default credentials in your~/.aws/credentials
file.
Since the username of a Cognito User can never change, this is used by the backend to match a Cognito User with a local Django User.
If a Django user is not found, one is created using the attributes fetched from Cognito. If an existing Django user is found, their attributes are updated.
If the boto3 client comes back with either a NotAuthorizedException
or
UserNotFoundException
, then None
is returned instead of a User.
Otherwise, the exception is raised.
Upon successful login, the three identity tokens returned from Cognito
(ID token, Refresh token, Access token) are stored in the user's request
session. In Django >= 1.11, this is done directly in the backend class.
Otherwise, this is done via the user_logged_in
signal.
Check the cdu directory for an example app with a login and user details page.
Setting the Django setting COGNITO_CREATE_UNKNOWN_USERS
to False
prevents the backend
from creating a new local Django user and only updates existing users.
If you create your own backend class that inhereits from CognitoBackend
, you may
want to also create your own custom user_logged_in
so that it checks
for the name of your custom class.
The APIKeyMiddleware
checks for a HTTP_AUTHORIZATION_ID
header
in the request and attaches it to the request object as api_key
.