Introduction to Basic Auth
Basic authentication (basic auth) is a method for an HTTP user agent (such as a web browser or client) to provide a username and password when making a request. This method commonly serves as a foundation for other authentication protocols due to its simplicity and effectiveness. In this guide, we will introduce basic auth, dive into multiple useful API operations, and provide a robust example application.
How Does Basic Auth Work?
Basic auth transmits credentials in an HTTP header encoded with Base64. Despite its simplicity, it’s essential to use it over HTTPS to ensure credentials’ security during transmission.
API Explanations and Code Snippets
1. Simple User Authentication
This endpoint verifies a user’s credentials.
GET /api/authenticate Authorization: Basic <base64-encoded-credentials> Response: { "authenticated": true, "user": { "id": "12345", "username": "johndoe" } }
2. Creating a New User
This endpoint allows the creation of a new user.
POST /api/users Content-Type: application/json Authorization: Basic <base64-encoded-admin-credentials> Request Body: { "username": "janesmith", "password": "password123" } Response: { "user": { "id": "67890", "username": "janesmith" } }
3. Retrieving User Details
Fetch details of the authenticated user.
GET /api/users/me Authorization: Basic <base64-encoded-credentials> Response: { "id": "12345", "username": "johndoe", "email": "johndoe@example.com" }
4. Updating User Password
Update the password for an authenticated user.
PUT /api/users/me/password Content-Type: application/json Authorization: Basic <base64-encoded-credentials> Request Body: { "old_password": "oldpassword123", "new_password": "newpassword456" } Response: { "message": "Password updated successfully" }
5. Deleting a User
Delete a user’s account.
DELETE /api/users/me Authorization: Basic <base64-encoded-credentials> Response: { "message": "User deleted successfully" }
Example Application Using Basic Auth APIs
Below is an example of a Python Flask application that utilizes the above APIs with basic auth.
from flask import Flask, request, jsonify from functools import wraps import base64 app = Flask(__name__) users = { "johndoe": {"password": "password123", "id": "12345"}, "janesmith": {"password": "password123", "id": "67890"} } def verify_auth(auth_header): auth_type, auth_info = auth_header.split() if auth_type.lower() != 'basic': return False, None username, password = base64.b64decode(auth_info).decode().split(':') user = users.get(username) if user and user['password'] == password: return True, username return False, None def require_auth(f): @wraps(f) def decorated(*args, **kwargs): auth_header = request.headers.get('Authorization') if not auth_header or not verify_auth(auth_header)[0]: return jsonify({"message": "Authentication required"}), 401 return f(*args, **kwargs) return decorated @app.route('/api/authenticate') def authenticate(): auth_header = request.headers.get('Authorization') authenticated, user = verify_auth(auth_header) if authenticated: return jsonify({"authenticated": True, "user": {"id": users[user]['id'], "username": user}}) return jsonify({"authenticated": False}), 401 @app.route('/api/users', methods=['POST']) @require_auth def create_user(): data = request.get_json() username = data['username'] password = data['password'] if username in users: return jsonify({"message": "User already exists"}), 400 user_id = str(len(users) + 1) users[username] = {"password": password, "id": user_id} return jsonify({"user": {"id": user_id, "username": username}}) @app.route('/api/users/me') @require_auth def get_user_details(): auth_header = request.headers.get('Authorization') _, username = verify_auth(auth_header) user = users[username] return jsonify({"id": user['id'], "username": username}) @app.route('/api/users/me/password', methods=['PUT']) @require_auth def update_password(): auth_header = request.headers.get('Authorization') _, username = verify_auth(auth_header) data = request.get_json() if users[username]['password'] != data['old_password']: return jsonify({"message": "Current password is incorrect"}), 400 users[username]['password'] = data['new_password'] return jsonify({"message": "Password updated successfully"}) @app.route('/api/users/me', methods=['DELETE']) @require_auth def delete_user(): auth_header = request.headers.get('Authorization') _, username = verify_auth(auth_header) del users[username] return jsonify({"message": "User deleted successfully"}) if __name__ == '__main__': app.run(debug=True)
This example demonstrates an HTTP API server implemented in Flask that requires basic auth for managing user accounts securely.
For production use, it’s recommended to integrate HTTPS and further security layers such as rate limiting and logging.
Hash: e89f63c4181bc584d1cb60c9eed03a60f937af8a40cbbada7beb8a21aeabc4b2