Storing passwords safely protects users from hackers. It keeps their accounts and data secure.
0
0
Password storage best practices in Flask
Introduction
When creating a user login system for a website or app.
When saving user passwords in a database.
When you want to prevent password theft if your database is hacked.
When you need to verify user identity securely.
When building any system that requires user authentication.
Syntax
Flask
from werkzeug.security import generate_password_hash, check_password_hash # To store a password securely hashed_password = generate_password_hash('user_password') # To check a password during login is_correct = check_password_hash(hashed_password, 'user_password')
generate_password_hash creates a safe hashed version of the password.
check_password_hash compares a stored hash with a password input.
Examples
This creates a hashed password string that looks random and safe to store.
Flask
hashed = generate_password_hash('mypassword123') print(hashed)
This checks if the password matches the stored hash.
Flask
check_password_hash(hashed, 'mypassword123') # returns True
This shows that a wrong password does not match the hash.
Flask
check_password_hash(hashed, 'wrongpassword') # returns False
Sample Program
This Flask app lets users register and login. Passwords are stored safely as hashes. Login checks the password against the stored hash.
Flask
from flask import Flask, request, jsonify from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) users = {} @app.route('/register', methods=['POST']) def register(): username = request.json.get('username') password = request.json.get('password') if username in users: return jsonify({'message': 'User already exists'}), 400 hashed = generate_password_hash(password) users[username] = hashed return jsonify({'message': 'User registered successfully'}) @app.route('/login', methods=['POST']) def login(): username = request.json.get('username') password = request.json.get('password') hashed = users.get(username) if not hashed or not check_password_hash(hashed, password): return jsonify({'message': 'Invalid username or password'}), 401 return jsonify({'message': 'Login successful'}) # To run the app: # flask run # Example usage: # POST /register with JSON {"username": "alice", "password": "secret123"} # POST /login with JSON {"username": "alice", "password": "secret123"}
OutputSuccess
Important Notes
Never store plain text passwords. Always hash them before saving.
Use a strong hashing function like the one in Werkzeug (Flask's helper library).
Do not try to create your own hashing method; use trusted libraries.
Summary
Always hash passwords before storing them to keep user data safe.
Use generate_password_hash and check_password_hash from Werkzeug in Flask.
Never store or log plain passwords anywhere in your app.