TL;DR
This guide shows you how to build a more secure login system for your web service using strong passwords, hashing, salting, and session management. It avoids storing passwords directly and protects against common attacks.
1. Password Storage: Hashing & Salting
Never store passwords in plain text! Use a one-way hash function with a unique salt for each password.
- Hashing: Transforms the password into an unreadable string.
- Salting: Adds a random value to each password before hashing, making rainbow table attacks much harder.
# Example using Python and bcrypt (install with 'pip install bcrypt')
import bcrypt
password = b"mysecretpassword"
salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(password, salt)
print(f"Salt: {salt}")
print(f"Hashed Password: {hashed_password}")
Store both the salt and hashed_password in your database.
2. Password Verification
When a user logs in, compare the hashed password they enter with the stored hash using the same salt.
# Example (Python & bcrypt)
import bcrypt
stored_salt = b'your_stored_salt'
hashed_password_from_db = b'your_hashed_password_from_db'
user_entered_password = b"mysecretpassword"
if bcrypt.checkpw(user_entered_password, hashed_password_from_db):
print("Password matches!")
else:
print("Incorrect password.")
3. Strong Password Policies
Enforce rules to make passwords harder to guess.
- Minimum Length: 8 characters or more (12+ is better).
- Complexity: Require a mix of uppercase, lowercase, numbers, and symbols.
- Avoid Common Passwords: Check against known compromised password lists.
You can use libraries to help with this validation.
4. Session Management
Once a user is authenticated, create a session to track their login status.
- Session ID: Generate a unique, random ID for each logged-in user.
- Secure Storage: Store the session ID in a secure cookie (
HttpOnlyandSecureflags). - Expiration: Set an expiration time for sessions to automatically log users out after inactivity.
Example using Flask (Python):
from flask import Flask, session, redirect, url_for
import os
app = Flask(__name__)
app.secret_key = os.urandom(24) # Important: Use a strong secret key!
@app.route('/login', methods=['POST'])
def login():
# ... (Authentication logic here - check password against hash)
if authentication_successful:
session['user_id'] = user_id # Store the user ID in the session
return redirect(url_for('home'))
else:
return "Invalid credentials."
5. Protection Against Common Attacks
- Brute-Force: Implement rate limiting to block excessive login attempts from the same IP address.
- Cross-Site Scripting (XSS): Sanitize user input and escape output to prevent malicious scripts.
- Cross-Site Request Forgery (CSRF): Use CSRF tokens in forms to verify requests originate from your site.
- SQL Injection: Use parameterized queries or an ORM to prevent attackers from injecting malicious SQL code.
6. Two-Factor Authentication (2FA)
Add an extra layer of security by requiring a second verification method, such as a code sent via SMS or an authenticator app.
- TOTP: Time-based One-Time Password using apps like Google Authenticator.
- SMS Codes: Send a unique code to the user’s phone number.

