Django Django Authentication & Security 2 — Questions and Answers
Question 1: What is Django's `AbstractUser` model used for?
- Extending the built-in User model with additional fields while keeping all default auth features (Correct answer)
- Creating users without database tables
- Defining permission groups
- Building API token-based authentication
Correct answer: Extending the built-in User model with additional fields while keeping all default auth features
AbstractUser allows you to add custom fields to Django's built-in user model by subclassing it, which is the recommended approach for custom user models.
Question 2: What does `logout(request)` do in Django?
- Clears the authenticated user from the session and flushes session data (Correct answer)
- Deletes the user's account
- Revokes all authentication tokens
- Redirects the user to the login page
Correct answer: Clears the authenticated user from the session and flushes session data
logout() removes the user's session data, ensuring they are fully logged out and protecting against session fixation attacks.
Question 3: What is the purpose of Django's `SecurityMiddleware`?
- Sets security headers like HSTS, X-Content-Type-Options, and enforces HTTPS (Correct answer)
- Sanitizes user input against XSS
- Encrypts session cookies
- Rate-limits requests per IP
Correct answer: Sets security headers like HSTS, X-Content-Type-Options, and enforces HTTPS
SecurityMiddleware handles several security-related HTTP headers and redirects HTTP to HTTPS based on settings like SECURE_HSTS_SECONDS and SECURE_SSL_REDIRECT.
Question 4: Which setting must be set to use a custom user model in Django?
- AUTH_USER_MODEL (Correct answer)
- CUSTOM_USER_MODEL
- USER_MODEL
- DEFAULT_USER_MODEL
Correct answer: AUTH_USER_MODEL
AUTH_USER_MODEL = 'myapp.CustomUser' must be set before the first migration to tell Django which model to use for authentication.
Question 5: What does Django's `check_password(raw_password, encoded)` function do?
- Verifies a plaintext password against a stored hashed password (Correct answer)
- Hashes a new password for storage
- Validates password strength against AUTH_PASSWORD_VALIDATORS
- Checks if a password has been compromised
Correct answer: Verifies a plaintext password against a stored hashed password
check_password() hashes the raw password using the same algorithm identified in the encoded hash and compares them securely using a constant-time comparison.
Question 6: What is Django's `UserCreationForm` used for?
- A built-in form for creating a new user with password confirmation (Correct answer)
- A form for user profile updates
- A form for resetting a user's password
- A form for granting user permissions
Correct answer: A built-in form for creating a new user with password confirmation
UserCreationForm provides username and two password fields with matching validation, and saves the user with a properly hashed password.
What is Django's `AbstractUser` model used for?