Django Authentication & Authorization

 

Django Authentication & Authorization — Custom User Model, Permissions, and Role-Based Access

Authentication and authorization are the backbone of any secure web application.

Whether you're building a SaaS product, admin dashboard, or REST API, managing users properly is critical.

In Django, authentication is built-in and production-ready but to build scalable systems, you must understand how to customize and extend it properly.

In this article, we’ll cover:

  • Django Authentication basics

  • Custom User Models

  • Permissions system

  • Role-based access control (RBAC)

  • Best practices for production

Authentication vs Authorization

Before diving in:

  • Authentication → Who are you? (Login system)

  • Authorization → What are you allowed to do? (Permissions)

Django provides tools for both.

Django’s Built-in Authentication System

Django ships with:

  • User model

  • Login/logout system

  • Password hashing

  • Session management

  • Admin integration

Basic example:

from django.contrib.auth import authenticate, login

user = authenticate(username='john', password='password123')

if user:
login(request, user)

Password hashing is secure by default — never stored in plain text.


Why You Should Use a Custom User Model

Many developers regret not creating a custom user model early.

By default, Django provides User with fields like:

  • username

  • email

  • password

  • first_name

  • last_name

But real-world applications often need:

  • Mobile number

  • Profile image

  • Company name

  • Role field

  • Authentication via email instead of username

Best practice:

Always create a custom user model at the beginning of the project.


Creating a Custom User Model

Step 1: Extend AbstractUser

from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
phone_number = models.CharField(max_length=15, blank=True)
role = models.CharField(max_length=20, default='user')

Step 2: Update settings.py

AUTH_USER_MODEL = 'accounts.CustomUser'

This ensures Django uses your model instead of the default one.

Protecting Views with Authentication

Use decorators:

from django.contrib.auth.decorators import login_required

@login_required
def dashboard(request):
return render(request, 'dashboard.html')

For Class-Based Views:

from django.contrib.auth.mixins import LoginRequiredMixin

class DashboardView(LoginRequiredMixin, TemplateView):
template_name = 'dashboard.html'

Django Permissions System

Django automatically creates permissions for every model:

  • add_model

  • change_model

  • delete_model

  • view_model

You can check permissions like this:

if request.user.has_perm('blog.add_post'):
# allow action

Custom Permissions

Inside your model:

class Post(models.Model):
title = models.CharField(max_length=200)

class Meta:
permissions = [
("can_publish", "Can publish post"),
]

Then assign permission via:

  • Admin panel

  • Code

Role-Based Access Control (RBAC)

Large applications use roles such as:

  • Admin

  • Editor

  • Author

  • User

There are two common approaches:

Approach 1: Using Groups (Recommended)

Django provides Groups out of the box.

Example:

  • Create group: "Editor"

  • Assign permissions to group

  • Assign users to group

Check role:

if request.user.groups.filter(name='Editor').exists():
# allow editing

Approach 2: Custom Role Field

If you added role in CustomUser:

if request.user.role == 'admin':
# allow access

This is simpler but less flexible than Groups.


Authorization in Class-Based Views

from django.contrib.auth.mixins import PermissionRequiredMixin

class PostCreateView(PermissionRequiredMixin, CreateView):
permission_required = 'blog.add_post'

Clean and production-ready.

Authentication in APIs

When building APIs using Django REST Framework, authentication options include:

  • Session Authentication

  • Token Authentication

  • JWT Authentication

  • OAuth

For scalable backend systems, JWT is commonly used.

Best Practices for Production

1. Always Use Custom User Model

Even if you don’t need extra fields now.

2. Never Store Passwords Manually

Use Django’s built-in hashing.

3. Use Groups for Role-Based Access

Cleaner and scalable.

4. Separate Authentication and Business Logic

Keep views clean.

5. Restrict Admin Access Carefully

Never expose sensitive models unnecessarily.

6. Use HTTPS in Production

Always protect session cookies.

Common Mistakes

❌ Modifying default User model later in project
❌ Writing role logic directly inside templates
❌ Skipping permission checks in APIs
❌ Trusting frontend role validation

Why Mastering Auth Matters

Authentication & Authorization knowledge is critical for:

  • SaaS platforms

  • Multi-user dashboards

  • Enterprise systems

  • Subscription-based products

  • REST APIs

Django provides a secure and extensible authentication system out of the box.

But real-world systems require:

  • Custom user models

  • Fine-grained permissions

  • Role-based access control

  • Secure API authentication


Comments

Popular posts from this blog

Database Integration in FastAPI (SQLAlchemy CRUD)

Middleware & CORS in FastAPI

Python Data Handling