Authentication and Authorization
Lesson 9: Authentication and Authorization in Django
In this lesson, we will explore how to implement user authentication and authorization in your Django application. Authentication is the process of verifying who a user is, while authorization determines what an authenticated user is allowed to do.
1. Setting Up Authentication
Django comes with a built-in authentication system that handles user accounts, groups, permissions, and cookie-based user sessions. To use this system, you need to ensure that the django.contrib.auth app is included in your INSTALLED_APPS setting (this is typically done by default).
Enabling Authentication
Make sure your settings.py has the following:
# settings.py
INSTALLED_APPS = [
...
'django.contrib.auth',
'django.contrib.contenttypes',
...
]
Creating User Accounts
You can create user accounts using the Django admin interface or programmatically using the User model. Here’s how to create a user programmatically:
from django.contrib.auth.models import User
# Create a new user
user = User.objects.create_user('username', 'user@example.com', 'password')
user.first_name = 'First'
user.last_name = 'Last'
user.save()
2. User Authentication Views
Django provides built-in views for user authentication. You can use these views to handle user login and logout.
Login View
To use the login view, you need to set up a URL pattern and a template:
# urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
urlpatterns = [
path('login/', auth_views.LoginView.as_view(), name='login'),
]
Login Template
Create a template registration/login.html:
<!-- registration/login.html -->
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
Logout View
To handle logout, add the following URL pattern:
# urls.py
urlpatterns += [
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]
3. User Authorization
Django's authorization system allows you to manage user permissions. You can assign permissions to users or groups and check permissions in your views.
Checking Permissions
You can check if a user has a specific permission using the user.has_perm() method:
# views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
if request.user.has_perm('app_name.permission_name'):
# Do something for users with permission
return render(request, 'template.html')
else:
return render(request, 'no_permission.html')
Using Decorators for Authorization
You can also use decorators to restrict access to views:
# views.py
from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: u.is_superuser)
def admin_view(request):
return render(request, 'admin_template.html')
Best Practices and Common Mistakes
Note: Always use HTTPS in production to protect user credentials during login.
Note: Ensure that your login forms include CSRF tokens to prevent CSRF attacks.
Note: Use Django's built-in user management features instead of rolling your own authentication system.
Conclusion
In this lesson, we covered how to implement user authentication and authorization in your Django application. We learned how to set up user accounts, use built-in authentication views, and manage user permissions effectively.
Exercises
- Exercise 1: Create a new user using the Django shell. Verify that the user is created by querying the User model.
- Exercise 2: Set up a login view and template. Test logging in with the user you created in Exercise 1.
- Exercise 3: Create a view that requires a user to be logged in and has a specific permission. Test the view with different user roles.
Summary
- Django provides a built-in authentication system for managing user accounts.
- User authentication can be handled using built-in views for login and logout.
- User authorization allows checking permissions and restricting access to views.
- Always use HTTPS and include CSRF tokens for security.