Django Django Authentication & Security 1 — Questions and Answers
Question 1: Which function authenticates a user with a username and password in Django?
- authenticate(request, username=username, password=password) (Correct answer)
- login(request, username, password)
- User.check_password(password)
- auth.verify(username, password)
Correct answer: authenticate(request, username=username, password=password)
authenticate() checks credentials against all configured authentication backends and returns a User object on success or None on failure.
Question 2: What does `login(request, user)` do in Django?
- Attaches the user to the session and marks them as logged in (Correct answer)
- Verifies the user's credentials
- Creates a new user account
- Generates an authentication token
Correct answer: Attaches the user to the session and marks them as logged in
login() saves the user's ID to the session using Django's session framework, establishing the logged-in state across requests.
Question 3: What does Django's CSRF middleware protect against?
- Cross-Site Request Forgery attacks where malicious sites submit requests on behalf of authenticated users (Correct answer)
- SQL injection via form inputs
- Cross-Site Scripting via template variables
- Brute-force login attacks
Correct answer: Cross-Site Request Forgery attacks where malicious sites submit requests on behalf of authenticated users
CSRF middleware validates a secret token in POST/PUT/DELETE requests to ensure they originate from the same site, not a malicious third-party page.
Question 4: Which Django setting controls password hashing algorithms?
- PASSWORD_HASHERS (Correct answer)
- PASSWORD_HASH_ALGORITHM
- AUTH_PASSWORD_HASHERS
- SECURITY_HASHERS
Correct answer: PASSWORD_HASHERS
PASSWORD_HASHERS is a list of hasher classes in priority order; Django uses the first one for new passwords and can upgrade older hashes automatically.
Question 5: What does `request.user.is_authenticated` return for an anonymous user?
- False (Correct answer)
- True
- None
- Raises AttributeError
Correct answer: False
For anonymous users, Django provides an AnonymousUser object whose is_authenticated property always returns False.
Question 6: Which decorator enforces that a view can only be accessed by users with a specific permission?
- @permission_required('app.permission_codename') (Correct answer)
- @requires_permission('permission_codename')
- @has_perm('permission_codename')
- @check_permission('permission_codename')
Correct answer: @permission_required('app.permission_codename')
permission_required() checks if the logged-in user has the specified permission and redirects to login if not, similar to @login_required.
Which function authenticates a user with a username and password in Django?