How To Create A Session Based Authentication In PHP

Session-based authentication module in Django:

Step 1: Create a Django app Create a new Django app using the following command:

					python startapp auth_module

Step 2: Update the settings In your Django project’s settings (, add the newly created app to the INSTALLED_APPS list:

    # ...
    # ...

Step 3: Create the authentication module Create a new file called in the auth_module directory with the following contents:

					from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

UserModel = get_user_model()

class AuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
            user = UserModel.objects.get(username=username)

            if user.check_password(password):
                return user
        except UserModel.DoesNotExist:

        return None

    def get_user(self, user_id):
            return UserModel.objects.get(pk=user_id)
        except UserModel.DoesNotExist:
            return None

Step 4: Update the authentication backend In your Django project’s settings (, update the AUTHENTICATION_BACKENDS setting to include the custom authentication backend:


Step 5: Protect your views In your views or Django Rest Framework views, you can protect your views by using the login_required decorator. For example:

					from django.contrib.auth.decorators import login_required
from django.shortcuts import render

def my_view(request):
    # Your view logic here
    return render(request, 'my_view.html')

That’s it! With these steps, you’ve set up a session-based authentication module in Django.

Please note that this is a basic setup, and you may need to customize it further based on your specific requirements. Additionally, you may want to handle user registration, password reset, and other authentication-related functionalities based on your application’s needs.