11. How do you handle user authentication and authorization in Django?

Basic

11. How do you handle user authentication and authorization in Django?

Overview

Handling user authentication and authorization is a fundamental aspect of web development, ensuring that users can securely access an application and are only able to perform actions that they have permission to. Django, a high-level Python web framework, provides a robust system for managing user authentication and authorization, making it easier for developers to secure their applications.

Key Concepts

  1. Authentication: Verifying the identity of a user. In Django, this typically involves checking a username and password.
  2. Authorization: Determining whether an authenticated user has permission to perform a certain action.
  3. User Model: Django's built-in user management system, which can be extended or replaced to meet specific requirements.

Common Interview Questions

Basic Level

  1. What is the difference between authentication and authorization in Django?
  2. How do you create a user in Django?

Intermediate Level

  1. How can you extend the default User model in Django?

Advanced Level

  1. How would you implement token-based authentication in a Django application?

Detailed Answers

1. What is the difference between authentication and authorization in Django?

Answer:
Authentication is the process of verifying who a user is, while authorization is the process of determining what actions an authenticated user is allowed to perform. Django uses its django.contrib.auth framework to handle both processes, where authentication checks a user's credentials (such as username and password), and authorization checks the permissions assigned to an authenticated user.

Key Points:
- Authentication verifies user identity.
- Authorization checks user permissions.
- Django's django.contrib.auth manages both.

Example:

# There's no direct C# example for Django, but the concept can be described in pseudo-code.
// Authentication example
if (username and password match database records) {
    // User is authenticated
}

// Authorization example
if (user has permission to perform action) {
    // User is authorized to perform the action
}

2. How do you create a user in Django?

Answer:
In Django, you can create a user programmatically using the create_user method of Django's UserManager, which is accessible through User.objects.create_user().

Key Points:
- create_user is used for creating users.
- Passwords are hashed automatically.
- You can set additional attributes like email.

Example:

from django.contrib.auth.models import User

# Creating a new user
user = User.objects.create_user('username', 'email@example.com', 'password')

# Setting additional attributes
user.first_name = 'John'
user.last_name = 'Doe'
user.save()

3. How can you extend the default User model in Django?

Answer:
To extend the default User model, you can either extend the existing User model using a one-to-one link with Django's OneToOneField or subclass AbstractUser to add additional fields and methods.

Key Points:
- Extending User model allows for additional user information.
- AbstractUser provides a way to extend the base User model while keeping Django's authentication framework.
- A one-to-one link to the User model is suitable for adding user profile information.

Example:

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

class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(null=True, blank=True)

4. How would you implement token-based authentication in a Django application?

Answer:
To implement token-based authentication, you would typically use Django Rest Framework (DRF), which provides built-in support for token authentication. You'd need to add 'rest_framework.authtoken' to your INSTALLED_APPS, run migrate to create the necessary database tables, and then configure the authentication classes to include TokenAuthentication.

Key Points:
- Django Rest Framework offers built-in token-based authentication.
- Tokens are stored in a database and passed via HTTP headers.
- Suitable for API authentication.

Example:

# settings.py configuration
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}

# Generating a token for a user
from rest_framework.authtoken.models import Token

token, created = Token.objects.get_or_create(user=user)

This guide highlights the foundational aspects of handling authentication and authorization in Django, providing a solid basis for interview preparation.