PYTHON

Log Failed Login Attempts for Security Audits (Python/Flask)

Learn to implement basic security logging in Flask applications to record and monitor failed login attempts, crucial for detecting brute-force attacks and improving incident response.

from flask import Flask, request, jsonify
import logging
from datetime import datetime

app = Flask(__name__)

# Configure logging
logging.basicConfig(
    filename='security.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

@app.route('/login', methods=['POST'])
def login():
    username = request.json.get('username')
    password = request.json.get('password')

    # Simulate user authentication
    if username == 'admin' and password == 'securepassword123': # In real app, use hashed passwords!
        logging.info(f'Successful login for user: {username} from IP: {request.remote_addr}')
        return jsonify({'message': 'Login successful'}), 200
    else:
        logging.warning(f'Failed login attempt for user: {username} from IP: {request.remote_addr}')
        return jsonify({'message': 'Invalid credentials'}), 401

@app.route('/')
def index():
    return 'Welcome to the secure app!'

if __name__ == '__main__':
    app.run(debug=True, port=5000)
How it works: This Flask snippet demonstrates how to implement basic security logging for failed login attempts. It configures Python's built-in `logging` module to write security-related events to a `security.log` file. When a user attempts to log in, the application checks their credentials (simulated here; in a real app, use secure password hashing and verification). On failure, a `WARNING` level message is logged, including the username and the IP address of the requester. Successful logins are logged at `INFO` level. This logging is vital for auditing, detecting brute-force attacks, and providing crucial information during security incident investigations.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs