Basic Auth
In this page:
How Basic Auth Works
When a browser requests a protected resource, Apache replies with a 401 Unauthorized status and a WWW-Authenticate header. The browser shows its built-in login prompt, then resends the request with an Authorization header containing the credentials, base64-encoded (not encrypted -- Basic Auth must always be paired with HTTPS to be safe over the network).
Creating a Password File
Apache checks credentials against a password file created with htpasswd, kept outside the DocumentRoot so it can never be downloaded directly. sudo htpasswd -c /etc/apache2/.htpasswd alice creates a new file with a first user (prompting for a password); drop the -c for additional users so you don't overwrite the file.
The Directives
Inside a <Directory> block (or .htaccess, if allowed): AuthType Basic selects Basic Auth, AuthName "Restricted Area" sets the text shown in the browser's login prompt, AuthUserFile /etc/apache2/.htpasswd points at the password file, and Require valid-user says any username/password pair in that file is accepted.
Restricting to Specific Users
Instead of Require valid-user, Require user alice bob only accepts those two specific usernames from the password file, even if other users exist in it -- useful when one shared .htpasswd file covers several protected areas with different allowed users.
Example: Password-protecting a directory
# Create the password file (first user)
# sudo htpasswd -c /etc/apache2/.htpasswd alice
<Directory "/var/www/example.com/admin">
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
</Directory>
{# Flagged by hand after confirming a runner can't handle this example
(a shell command / go.mod file stored as a TopicExample, a language
feature the configured runner version doesn't support, or output
that blows a runner's sandbox limit) -- see TopicExample.norun.
Never render the run button for these, regardless of language,
since it would just fail at execute_code (or worse, hang the
Judge0 queue on a submission that can never finish cleanly). #}
- Storing the .htpasswd file inside the public DocumentRoot, where a misconfiguration could let someone download and crack it offline.
- Using HTTP Basic Auth over plain HTTP in production, exposing credentials to anyone able to observe the network traffic.
- Re-running
htpasswdwith-cfor a second user, which overwrites the file and deletes the first user instead of adding to it.
Chapter Quiz — Complete all 4 topics to unlock
0/4 topics done
Complete these topics first: