BASIC HTTP AUTHENTICATION
Basic Authentication is a simple HTTP authentication mechanism where a web page or resource requires a username and password to grant access. The credentials are sent in the HTTP headers encoded in Base64.
APACHE (.HTACCESS)
#Create a .htaccess file in the directory to be protected
root@engineering:~$ nano .htaccess
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/.htpasswd
Require valid-user
#Create a .htpasswd file to store user credentials
root@ngineering:~$ nano .htpasswd
htpasswd -c /path/to/.htpasswd username
#restart apache server
root@engineering:~$ sudo systemctl restart apache2
#Ensure the .htaccess feature is enabled in Apache by verifying the AllowOverride directive is properly configured in your Apache configuration files (e.g., /etc/apache2/sites-available/000-default.conf).
root@engineering:~$ nano /etc/apache2/sites-available/000-default.conf
<Directory /var/www/html>
AllowOverride All
</Directory>
#Reload Apache after making configuration changes:
root@ngineering:~$ sudo systemctl reload apache2
#
root@engineering:~$ curl -u username:password http://www.example.com/protected-resource
NGINX
#Modify the Nginx Configuration
root@engineering:~$ nano /etc/nginx/sites-available/example.conf
* ALT: /etc/nginx/nginx.conf
server {
listen 80;
server_name example.com;
location /protected/ {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
# Other server configurations...
}
#Create the .htpasswd File
#The .htpasswd file stores the username and encrypted password for basic authentication
root@engineering:~$ sudo apt update
root@engineering:~$ sudo apt install apache2-utils
root@engineering:~$ nano .htpasswd
root@engineering:~$ sudo htpasswd -c /etc/nginx/.htpasswd username
#to add more users
root@engineering:~$ sudo htpasswd /etc/nginx/.htpasswd newuser
#test nginx configuration
root@engineering:~$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
root@engineering:~$ sudo systemctl restart nginx
root@engineering:~$ curl -u username:password http://www.example.com/protected-resource
FLASK
root@engineering:~$
from flask import Flask, request, Response
app = Flask(__name__)
def check_auth(username, password):
return username == 'admin' and password == 'password'
def authenticate():
return Response(
'Could not verify your access level.\n', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
@app.route('/protected')
def protected():
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return "Hello, you have access!"
if __name__ == '__main__':
app.run()
Last updated