Welcome to dj-rest-auth’s documentation!¶
Note
dj-rest-auth version 1.0.0 now uses Django Simple JWT.
Contents¶
Introduction¶
Since the introduction of django-rest-framework, Django apps have been able to serve up app-level REST API endpoints. As a result, we saw a lot of instances where developers implemented their own REST registration API endpoints here and there, snippets, and so on. We aim to solve this demand by providing dj-rest-auth, a set of REST API endpoints to handle User Registration and Authentication tasks. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for User Management. Of course, we’ll add more API endpoints as we see the demand.
Features¶
- User Registration with activation
- Login/Logout
- Retrieve/Update the Django User model
- Password change
- Password reset via e-mail
- Social Media authentication
Apps structure¶
dj_rest_auth
has basic auth functionality like login, logout, password reset and password changedj_rest_auth.registration
has logic related with registration and social media authentication
Demo projects¶
- You can also check our Demo Project which is using jQuery on frontend.
- There is also a React demo project based on Create-React-App in demo/react-spa/
Installation¶
- Install package:
pip install dj-rest-auth
- Add
dj_rest_auth
app to INSTALLED_APPS in your django settings.py:
INSTALLED_APPS = (
...,
'rest_framework',
'rest_framework.authtoken',
...,
'dj_rest_auth'
)
Note
This project depends on django-rest-framework
library, so install it if you haven’t done yet. Make sure also you have installed rest_framework
and rest_framework.authtoken
apps
- Add dj_rest_auth urls:
urlpatterns = [
...,
path('dj-rest-auth/', include('dj_rest_auth.urls'))
]
- Migrate your database
python manage.py migrate
You’re good to go now!
Registration (optional)¶
- If you want to enable standard registration process you will need to install
django-allauth
by usingpip install 'dj-rest-auth[with_social]'
. - Add
django.contrib.sites
,allauth
,allauth.account
,allauth.socialaccount
anddj_rest_auth.registration
apps to INSTALLED_APPS in your django settings.py: - Add
SITE_ID = 1
to your django settings.py
INSTALLED_APPS = (
...,
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'dj_rest_auth.registration',
)
SITE_ID = 1
- Add dj_rest_auth.registration urls:
urlpatterns = [
...,
path('dj-rest-auth/', include('dj_rest_auth.urls')),
path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls'))
]
JSON Web Token (JWT) Support (optional)¶
By default dj-rest-auth
uses Django’s Token-based authentication. If you want to use JWT authentication, follow these steps:
- Install djangorestframework-simplejwt
djangorestframework-simplejwt
is currently the only supported JWT library.
- Add a simple_jwt auth configuration to the list of authentication classes.
REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': (
...
'dj_rest_auth.jwt_auth.JWTCookieAuthentication',
)
...
}
- Add the following configuration value to your settings file to enable JWT authentication in dj-rest-auth.
REST_AUTH = {
...
'USE_JWT': True,
}
- Declare what you want the cookie key to be called. If you want to use the refresh token feature, also be sure to set that variable.
REST_AUTH = {
...
'JWT_AUTH_COOKIE': 'my-app-auth',
'JWT_AUTH_REFRESH_COOKIE': 'my-refresh-token',
}
This example value above will cause dj-rest-auth to return a Set-Cookie header that looks like this:
Set-Cookie: my-app-auth=xxxxxxxxxxxxx; expires=Sat, 28 Mar 2020 18:59:00 GMT; HttpOnly; Max-Age=300; Path=/
If JWT_AUTH_REFRESH_COOKIE
is also set, it will also set a comparable cookie for that. JWT_AUTH_COOKIE
is also used while authenticating each request against protected views.
API endpoints¶
Basic¶
/dj-rest-auth/login/ (POST)
- username
- password
Returns Token key
/dj-rest-auth/logout/ (POST)
Note
ACCOUNT_LOGOUT_ON_GET = True
to allow logout using GET - this is the exact same configuration from allauth. NOT recommended, see: http://django-allauth.readthedocs.io/en/latest/views.html#logout/dj-rest-auth/password/reset/ (POST)
/dj-rest-auth/password/reset/confirm/ (POST)
- uid
- token
- new_password1
- new_password2
Note
uid and token are sent in email after calling /dj-rest-auth/password/reset/
/dj-rest-auth/password/change/ (POST)
- new_password1
- new_password2
- old_password
Note
OLD_PASSWORD_FIELD_ENABLED = True
to use old_password.Note
LOGOUT_ON_PASSWORD_CHANGE = False
to keep the user logged in after password change/dj-rest-auth/user/ (GET, PUT, PATCH)
- username
- first_name
- last_name
Returns pk, username, email, first_name, last_name
/dj-rest-auth/token/verify/ (POST)
- token
Returns an empty JSON object.
Note
USE_JWT = True
to use token/verify/ route.Note
Takes a token and indicates if it is valid. This view provides no information about a token’s fitness for a particular use. Will return a
HTTP 200 OK
in case of a valid token andHTTP 401 Unauthorized
with{"detail": "Token is invalid or expired", "code": "token_not_valid"}
in case of a invalid or expired token./dj-rest-auth/token/refresh/ (POST) (see also)
- refresh
Returns access
Note
USE_JWT = True
to use token/refresh/ route.Note
Takes a refresh type JSON web token and returns an access type JSON web token if the refresh token is valid.
HTTP 401 Unauthorized
with{"detail": "Token is invalid or expired", "code": "token_not_valid"}
in case of a invalid or expired token.
Registration¶
/dj-rest-auth/registration/ (POST)
- username
- password1
- password2
/dj-rest-auth/registration/verify-email/ (POST)
- key
Note
If you set account email verification as mandatory, you have to add the VerifyEmailView with the used name. You need to import the view:
from dj_rest_auth.registration.views import VerifyEmailView
. Then add the url with the corresponding name:path('dj-rest-auth/account-confirm-email/', VerifyEmailView.as_view(), name='account_email_verification_sent')
to the urlpatterns list./dj-rest-auth/registration/resend-email/ (POST)
Resends the email verification
Social Media Authentication¶
Basing on example from installation section Installation
/dj-rest-auth/facebook/ (POST)
- access_token
- code
Note
access_token
ORcode
can be used as standalone arguments, see https://github.com/iMerica/dj-rest-auth/blob/master/dj_rest_auth/registration/views.py/dj-rest-auth/twitter/ (POST)
- access_token
- token_secret
Configuration¶
dj-rest-auth behaviour can be controlled by adjust settings in settings.py
:
# Django project settings.py
...
REST_AUTH = {
'LOGIN_SERIALIZER': 'dj_rest_auth.serializers.LoginSerializer',
'TOKEN_SERIALIZER': 'dj_rest_auth.serializers.TokenSerializer',
'JWT_SERIALIZER': 'dj_rest_auth.serializers.JWTSerializer',
'JWT_SERIALIZER_WITH_EXPIRATION': 'dj_rest_auth.serializers.JWTSerializerWithExpiration',
'JWT_TOKEN_CLAIMS_SERIALIZER': 'rest_framework_simplejwt.serializers.TokenObtainPairSerializer',
'USER_DETAILS_SERIALIZER': 'dj_rest_auth.serializers.UserDetailsSerializer',
'PASSWORD_RESET_SERIALIZER': 'dj_rest_auth.serializers.PasswordResetSerializer',
'PASSWORD_RESET_CONFIRM_SERIALIZER': 'dj_rest_auth.serializers.PasswordResetConfirmSerializer',
'PASSWORD_CHANGE_SERIALIZER': 'dj_rest_auth.serializers.PasswordChangeSerializer',
'REGISTER_SERIALIZER': 'dj_rest_auth.registration.serializers.RegisterSerializer',
'REGISTER_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),
'TOKEN_MODEL': 'rest_framework.authtoken.models.Token',
'TOKEN_CREATOR': 'dj_rest_auth.utils.default_create_token',
'PASSWORD_RESET_USE_SITES_DOMAIN': False,
'OLD_PASSWORD_FIELD_ENABLED': False,
'LOGOUT_ON_PASSWORD_CHANGE': False,
'SESSION_LOGIN': True,
'USE_JWT': False,
'JWT_AUTH_COOKIE': None,
'JWT_AUTH_REFRESH_COOKIE': None,
'JWT_AUTH_REFRESH_COOKIE_PATH': '/',
'JWT_AUTH_SECURE': False,
'JWT_AUTH_HTTPONLY': True,
'JWT_AUTH_SAMESITE': 'Lax',
'JWT_AUTH_RETURN_EXPIRATION': False,
'JWT_AUTH_COOKIE_USE_CSRF': False,
'JWT_AUTH_COOKIE_ENFORCE_CSRF_ON_UNAUTHENTICATED': False,
}
Above, the default values for these settings are shown.
LOGIN_SERIALIZER
¶
The path to the serializer class for the login in
dj_rest_auth.views.LoginView
. The value is the dotted path to
dj_rest_auth.serializers.LoginSerializer
, which is also the default.
TOKEN_SERIALIZER
¶
The path to the serializer class for the Token response on successful
authentication in dj_rest_auth.views.LoginView
. The value is the dotted
path to dj_rest_auth.serializers.TokenSerializer
, which is also the
default.
JWT_SERIALIZER
¶
The path to the serializer class for the JWT response on successful
authentication in dj_rest_auth.views.LoginView
. The value is the dotted
path to dj_rest_auth.serializers.JWTSerializer
, which is also the default.
Requires USE_JWT=True
in settings.
JWT_SERIALIZER_WITH_EXPIRATION
¶
The path to the serializer class for the JWT response with its expiration time
on successful authentication in dj_rest_auth.views.LoginView
. The value is
the dotted path to dj_rest_auth.serializers.JWTSerializerWithExpiration
,
which is also the default. Requires USE_JWT=True
in settings.
JWT_TOKEN_CLAIMS_SERIALIZER
¶
The path to the serializer class for the JWT Claims on successful
authentication in dj_rest_auth.views.LoginView
. The value is the dotted
path to rest_framework_simplejwt.serializers.TokenObtainPairSerializer
,
which is also the default. Requires USE_JWT=True
in settings.
USER_DETAILS_SERIALIZER
¶
The path to the serializer class for the User details in
dj_rest_auth.views.UserDetailsView
. The value is the dotted path to
dj_rest_auth.serializers.UserDetailsSerializer
, which is also the default.
PASSWORD_RESET_SERIALIZER
¶
The path to the serializer class for the password reset in
dj_rest_auth.views.PasswordResetView
. The value is the dotted path to
dj_rest_auth.serializers.PasswordResetSerializer
, which is also the
default.
PASSWORD_RESET_CONFIRM_SERIALIZER
¶
The path to the serializer class for the password reset confirm in
dj_rest_auth.views.PasswordResetConfirmView
. The value is the dotted path to
dj_rest_auth.serializers.PasswordResetConfirmSerializer
, which is also the
default.
PASSWORD_CHANGE_SERIALIZER
¶
The path to the serializer class for the password change in
dj_rest_auth.views.PasswordChangeView
. The value is the dotted path to
dj_rest_auth.serializers.PasswordChangeSerializer
, which is also the
default.
REGISTER_SERIALIZER
¶
The path to the serializer class for the register in
dj_rest_auth.registration.views.RegisterView
. The value is the dotted path
to dj_rest_auth.registration.serializers.RegisterSerializer
, which is also
the default.
Note
The custom REGISTER_SERIALIZER
must define a def save(self, request)
method that returns a user model instance.
REGISTER_PERMISSION_CLASSES
¶
A tuple that contains paths to the permission classes for the register in
dj_rest_auth.registration.views.RegisterView
. The value is the dotted path
to path.to.another.permission.class
.
rest_framework.permissions.AllowAny
is included by default.
TOKEN_MODEL
¶
The path to the model class for the token. The value is the dotted path to
rest_framework.authtoken.models.Token
, which is also the default. If set to
None
token authentication will be disabled. In this case at least one of
SESSION_LOGIN
or USE_JWT
must be enabled.
TOKEN_CREATOR
¶
The path to callable for creating tokens. The value is the dotted path to
dj_rest_auth.utils.default_create_token
, which is also the default.
PASSWORD_RESET_USE_SITES_DOMAIN
¶
If set to True
, the domain in the password reset e-mail will be set to the
domain you defined in django.contrib.sites
module with SITE_ID=1
.
Default is False
.
OLD_PASSWORD_FIELD_ENABLED
¶
If set to True
, old password verification in
dj_rest_auth.views.PasswordChangeView
will be added. Default is False
.
LOGOUT_ON_PASSWORD_CHANGE
¶
If set to True
, current user will be logged out after a password change.
Default is False
.
SESSION_LOGIN
¶
If set to True
, session login in dj_rest_auth.views.LoginView
will be
enabled. Default is True
.
USE_JWT
¶
If set to True
, JWT Authentication in dj_rest_auth.views.LoginView
will
be used instead of Token or Session based login. Default is False
.
Note
JWT Authentication in dj-rest-auth is built on top of djangorestframework-simplejwt https://github.com/SimpleJWT/django-rest-framework-simplejwt. You must install it in order to be able to use JWT Authentication in dj-rest-auth.
JWT_AUTH_COOKIE
¶
The cookie name for access_token
from JWT Authentication. Default is
None
.
JWT_AUTH_REFRESH_COOKIE
¶
The cookie name for refresh_token
from JWT Authentication. Default is
None
.
JWT_AUTH_REFRESH_COOKIE_PATH
¶
The cookie path for refresh_token
from JWT Authentication. Default is
'/'
.
JWT_AUTH_SECURE
¶
If set to True
, the cookie will only be sent through https scheme. Default
is False
.
JWT_AUTH_HTTPONLY
¶
If set to True
, the client-side JavaScript will not be able to access the
cookie. Default is True
.
Note
refresh_token
will not be sent if JWT_AUTH_HTTPONLY
set to True
, set it to False
if you need refresh_token
.
JWT_AUTH_SAMESITE
¶
To tell the browser not to send this cookie when performing a cross-origin
request. Default is 'Lax'
. SameSite isn’t supported by all browsers.
JWT_AUTH_RETURN_EXPIRATION
¶
If set to True
, the access_token
and refresh_token
expiration time
will be included in response on successful JWT Authentication in
dj_rest_auth.views.LoginView
. Default is False
.
JWT_AUTH_COOKIE_USE_CSRF
¶
If set to True
, enable CSRF checks for only authenticated views when using
the JWT cookie for auth. Does not effect a client’s ability to authenticate
using a JWT Bearer Auth header without a CSRF token. Default is False
.
JWT_AUTH_COOKIE_ENFORCE_CSRF_ON_UNAUTHENTICATED
¶
If set to True
, enables CSRF checks for authenticated and unauthenticated
views when using the JWT cookie for auth. It does not effect a client’s ability
to authenticate using a JWT Bearer Auth header without a CSRF token (though
getting the JWT token in the first place without passing a CSRF token isnt
possible). Default is False
.
Demo project¶
This demo project shows how you can potentially use dj-rest-auth app with jQuery on frontend. To run this locally follow the steps below.
cd /tmp
git clone https://github.com/iMerica/dj-rest-auth.git
cd dj-rest-auth/demo/
pip install -r requirements.pip
python manage.py migrate --settings=demo.settings --noinput
python manage.py runserver --settings=demo.settings
Now, go to http://127.0.0.1:8000/
in your browser. There is also a
Single Page Application (SPA) in React within the demo/
directory. To run this do:
cd react-spa/
yarn # or npm install
yarn run start
Now, go to https://localhost:3000
in your browser to view it.
FAQ¶
Why account_confirm_email url is defined but it is not usable?
In /dj_rest_auth/registration/urls.py we can find something like this:
url(r'^account-confirm-email/(?P<key>[-:\w]+)/$', TemplateView.as_view(), name='account_confirm_email'),
This url is used by django-allauth. Empty TemplateView is defined just to allow reverse() call inside app - when email with verification link is being sent.
You should override this view/url to handle it in your API client somehow and then, send post to /verify-email/ endpoint with proper key. If you don’t want to use API on that step, then just use ConfirmEmailView view from: django-allauth https://github.com/pennersr/django-allauth/blob/master/allauth/account/views.py
I get an error: Reverse for ‘password_reset_confirm’ not found.
You need to add password_reset_confirm url into your
urls.py
(at the top of any other included urls). Please check theurls.py
module inside demo app example for more details.How can I update UserProfile assigned to User model?
Assuming you already have UserProfile model defined like this
from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, related_name='userprofile') # custom fields for user company_name = models.CharField(max_length=100)
To allow update user details within one request send to dj_rest_auth.views.UserDetailsView view, create serializer like this:
from rest_framework import serializers from dj_rest_auth.serializers import UserDetailsSerializer class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('company_name',) class UserSerializer(UserDetailsSerializer): profile = UserProfileSerializer(source="userprofile") class Meta(UserDetailsSerializer.Meta): fields = UserDetailsSerializer.Meta.fields + ('profile',) def update(self, instance, validated_data): userprofile_serializer = self.fields['profile'] userprofile_instance = instance.userprofile userprofile_data = validated_data.pop('userprofile', {}) # to access the 'company_name' field in here # company_name = userprofile_data.get('company_name') # update the userprofile fields userprofile_serializer.update(userprofile_instance, userprofile_data) instance = super().update(instance, validated_data) return instance
And setup USER_DETAILS_SERIALIZER in django settings:
REST_AUTH = { ... 'USER_DETAILS_SERIALIZER': 'demo.serializers.UserSerializer', }
Vulnerability Disclosure Policy¶
Please observe the standard best practices of responsible disclosure, especially considering that this is OSS. See OWASP’s disclosure cheat sheet.
Some basic rules:
- Keep it legal.
- Respect everyone’s privacy.
- Contact the core maintainer(s) immediately if you discover a serious security vulnerability (imichael@pm.me for now).
Social Authentication (optional)¶
Using
django-allauth
,dj-rest-auth
provides helpful class for creating social media authentication view.Note
Points 1 and 2 are related to
django-allauth
configuration, so if you have already configured social authentication, then please go to step 3. Seedjango-allauth
documentation for more details.allauth.socialaccount
andallauth.socialaccount.providers.facebook
orallauth.socialaccount.providers.twitter
apps to INSTALLED_APPS in your django settings.py:Facebook¶
dj_rest_auth.registration.views.SocialLoginView
withFacebookOAuth2Adapter
adapter as an attribute:Twitter¶
If you are using Twitter for your social authentication, it is a bit different since Twitter uses OAuth 1.0.
dj_rest_auth.registration.views.SocialLoginView
withTwitterOAuthAdapter
adapter andTwitterLoginSerializer
as an attribute:Note
Starting from v0.21.0, django-allauth has dropped support for context processors. Check out http://django-allauth.readthedocs.org/en/latest/changelog.html#from-0-21-0 for more details.
GitHub¶
If you are using GitHub for your social authentication, it uses code and not AccessToken directly.
dj_rest_auth.views.SocialLoginView
withGitHubOAuth2Adapter
adapter, anOAuth2Client
and a callback_url as attributes:Google¶
If you are using Google for your social authentication, you can choose
Authorization Code Grant
orImplicit Grant
(deprecated). Serializer of dj-rest-auth accepts bothcode
andtoken
allauth.socialaccount
andallauth.socialaccount.providers.google
apps to INSTALLED_APPS in your django settings.py:dj_rest_auth.views.SocialLoginView
withGoogleOAuth2Adapter
adapter, anOAuth2Client
and a callback_url as attributes:5. Retrive code (or token) By accessing Google’s endpoint, you can get
code
ortoken
If you’re using Authorization Code Grant, you can get code from following URL
https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=<CALLBACK_URL_YOU_SET_ON_GOOGLE>&prompt=consent&response_type=code&client_id=<YOUR CLIENT ID>&scope=openid%20email%20profile&access_type=offline
If you’re using Implicit Grant, you can get token from following URL
https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=<CALLBACK_URL_YOU_SET_ON_GOOGLE>&prompt=consent&response_type=token&client_id=<YOUR CLIENT ID>&scope=openid%20email%20profile
Additional Social Connect Views¶
If you want to allow connecting existing accounts in addition to login, you can use connect views:
In urls.py:
You can also use the following views to check all social accounts attached to the current authenticated user and disconnect selected social accounts: