├── .gitignore ├── README.md ├── django ├── drfauth │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py └── users │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ └── __init__.py │ ├── models.py │ ├── serializers.py │ ├── tests.py │ └── views.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | __pycache__ 3 | django/db.sqlite3 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Example project showing how to implement Django Rest Framework authentication in your web application by leveraging the built-in Django session framework. 2 | 3 | This approach is way simpler (and secure) than other popular methods such as JWT, and has only one requirement: your frontend (think Vue.js, React, ...) and your backend should be served by the same domain. 4 | 5 | A more detailed explaination can be found in my tutorial: 6 | 7 | ### [Django Rest Framework Authentication: the easy way](https://www.guguweb.com/2022/01/23/django-rest-framework-authentication-the-easy-way/) 8 | -------------------------------------------------------------------------------- /django/drfauth/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/baxeico/drf-authentication/129da63eeb0af387283b54b7fe68d11658030790/django/drfauth/__init__.py -------------------------------------------------------------------------------- /django/drfauth/asgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | ASGI config for drfauth project. 3 | 4 | It exposes the ASGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.asgi import get_asgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'drfauth.settings') 15 | 16 | application = get_asgi_application() 17 | -------------------------------------------------------------------------------- /django/drfauth/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for drfauth project. 3 | 4 | Generated by 'django-admin startproject' using Django 3.2.11. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/3.2/ref/settings/ 11 | """ 12 | 13 | from pathlib import Path 14 | 15 | # Build paths inside the project like this: BASE_DIR / 'subdir'. 16 | BASE_DIR = Path(__file__).resolve().parent.parent 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'django-insecure-pebx)$jajjt0pujhjxv3tqd4wp%)0m!m@=uf!2gplqs_)a54am' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'rest_framework', 41 | 'users', 42 | ] 43 | 44 | MIDDLEWARE = [ 45 | 'django.middleware.security.SecurityMiddleware', 46 | 'django.contrib.sessions.middleware.SessionMiddleware', 47 | 'django.middleware.common.CommonMiddleware', 48 | 'django.middleware.csrf.CsrfViewMiddleware', 49 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 50 | 'django.contrib.messages.middleware.MessageMiddleware', 51 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 52 | ] 53 | 54 | ROOT_URLCONF = 'drfauth.urls' 55 | 56 | TEMPLATES = [ 57 | { 58 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 59 | 'DIRS': [], 60 | 'APP_DIRS': True, 61 | 'OPTIONS': { 62 | 'context_processors': [ 63 | 'django.template.context_processors.debug', 64 | 'django.template.context_processors.request', 65 | 'django.contrib.auth.context_processors.auth', 66 | 'django.contrib.messages.context_processors.messages', 67 | ], 68 | }, 69 | }, 70 | ] 71 | 72 | WSGI_APPLICATION = 'drfauth.wsgi.application' 73 | 74 | 75 | # Database 76 | # https://docs.djangoproject.com/en/3.2/ref/settings/#databases 77 | 78 | DATABASES = { 79 | 'default': { 80 | 'ENGINE': 'django.db.backends.sqlite3', 81 | 'NAME': BASE_DIR / 'db.sqlite3', 82 | } 83 | } 84 | 85 | 86 | # Password validation 87 | # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators 88 | 89 | AUTH_PASSWORD_VALIDATORS = [ 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ] 103 | 104 | 105 | # Internationalization 106 | # https://docs.djangoproject.com/en/3.2/topics/i18n/ 107 | 108 | LANGUAGE_CODE = 'en-us' 109 | 110 | TIME_ZONE = 'UTC' 111 | 112 | USE_I18N = True 113 | 114 | USE_L10N = True 115 | 116 | USE_TZ = True 117 | 118 | 119 | # Static files (CSS, JavaScript, Images) 120 | # https://docs.djangoproject.com/en/3.2/howto/static-files/ 121 | 122 | STATIC_URL = '/static/' 123 | 124 | # Default primary key field type 125 | # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field 126 | 127 | DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' 128 | 129 | # Django Rest Framework settings 130 | 131 | REST_FRAMEWORK = { 132 | 'DEFAULT_AUTHENTICATION_CLASSES': [ 133 | 'rest_framework.authentication.SessionAuthentication', 134 | ], 135 | 'DEFAULT_PERMISSION_CLASSES': [ 136 | 'rest_framework.permissions.IsAuthenticated', 137 | ], 138 | } 139 | -------------------------------------------------------------------------------- /django/drfauth/urls.py: -------------------------------------------------------------------------------- 1 | """drfauth URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/3.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path 18 | 19 | from users import views 20 | 21 | urlpatterns = [ 22 | path('admin/', admin.site.urls), 23 | path('login/', views.LoginView.as_view()), 24 | path('profile/', views.ProfileView.as_view()), 25 | ] 26 | -------------------------------------------------------------------------------- /django/drfauth/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for drfauth project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'drfauth.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /django/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | """Run administrative tasks.""" 9 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'drfauth.settings') 10 | try: 11 | from django.core.management import execute_from_command_line 12 | except ImportError as exc: 13 | raise ImportError( 14 | "Couldn't import Django. Are you sure it's installed and " 15 | "available on your PYTHONPATH environment variable? Did you " 16 | "forget to activate a virtual environment?" 17 | ) from exc 18 | execute_from_command_line(sys.argv) 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /django/users/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/baxeico/drf-authentication/129da63eeb0af387283b54b7fe68d11658030790/django/users/__init__.py -------------------------------------------------------------------------------- /django/users/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /django/users/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class UsersConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'users' 7 | -------------------------------------------------------------------------------- /django/users/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/baxeico/drf-authentication/129da63eeb0af387283b54b7fe68d11658030790/django/users/migrations/__init__.py -------------------------------------------------------------------------------- /django/users/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /django/users/serializers.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth import authenticate 2 | from django.contrib.auth.models import User 3 | 4 | from rest_framework import serializers 5 | 6 | class LoginSerializer(serializers.Serializer): 7 | """ 8 | This serializer defines two fields used for authentication: username and password. 9 | It will try to authenticate the user with username/password when validated. 10 | """ 11 | username = serializers.CharField( 12 | label="Username", 13 | write_only=True 14 | ) 15 | password = serializers.CharField( 16 | label="Password", 17 | style={'input_type': 'password'}, # This will be used when the DRF browsable API is enabled 18 | trim_whitespace=False, 19 | write_only=True 20 | ) 21 | 22 | def validate(self, attrs): 23 | # Take username and password from request 24 | username = attrs.get('username') 25 | password = attrs.get('password') 26 | 27 | if username and password: 28 | # Try to authenticate the user using Django auth framework. 29 | user = authenticate(request=self.context.get('request'), 30 | username=username, password=password) 31 | if not user: 32 | # If we don't have a regular user, raise a ValidationError 33 | msg = 'Access denied: wrong username or password.' 34 | raise serializers.ValidationError(msg, code='authorization') 35 | else: 36 | msg = 'Both "username" and "password" are required.' 37 | raise serializers.ValidationError(msg, code='authorization') 38 | # We have a valid user, put it in the serializer's validated_data. 39 | # It will be used in the view. 40 | attrs['user'] = user 41 | return attrs 42 | 43 | 44 | class UserSerializer(serializers.ModelSerializer): 45 | 46 | class Meta: 47 | model = User 48 | fields = [ 49 | 'username', 50 | 'email', 51 | 'first_name', 52 | 'last_name', 53 | ] 54 | -------------------------------------------------------------------------------- /django/users/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /django/users/views.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth import login, logout 2 | 3 | from rest_framework import generics 4 | from rest_framework import permissions 5 | from rest_framework import status 6 | from rest_framework import views 7 | from rest_framework.response import Response 8 | 9 | from . import serializers 10 | 11 | class LoginView(views.APIView): 12 | # This view should be accessible also for unauthenticated users. 13 | permission_classes = (permissions.AllowAny,) 14 | 15 | def post(self, request, format=None): 16 | serializer = serializers.LoginSerializer(data=self.request.data, context={ 'request': self.request }) 17 | serializer.is_valid(raise_exception=True) 18 | user = serializer.validated_data['user'] 19 | login(request, user) 20 | return Response(None, status=status.HTTP_202_ACCEPTED) 21 | 22 | 23 | class LogoutView(views.APIView): 24 | 25 | def post(self, request, format=None): 26 | logout(request) 27 | return Response(None, status=status.HTTP_204_NO_CONTENT) 28 | 29 | 30 | class ProfileView(generics.RetrieveAPIView): 31 | serializer_class = serializers.UserSerializer 32 | 33 | def get_object(self): 34 | return self.request.user 35 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | asgiref==3.4.1 2 | Django==3.2.11 3 | django-rest-framework==0.1.0 4 | djangorestframework==3.13.1 5 | pkg_resources==0.0.0 6 | pytz==2021.3 7 | sqlparse==0.4.2 8 | typing_extensions==4.0.1 9 | --------------------------------------------------------------------------------