How to store username and password in Flask

How to store username and password in Flask

Storing usernames and passwords in a Flask application requires careful consideration for security. Here's a general approach to safely handle this information:

  1. Use Environment Variables for Configuration: Store sensitive configuration details (like database URI, secret keys, etc.) in environment variables, not in your source code.

  2. Database Setup: Use a database to store user data. SQL databases like PostgreSQL, MySQL, or SQLite, or NoSQL databases like MongoDB can be used.

  3. Hash Passwords: Never store plain-text passwords. Use a strong hashing algorithm like bcrypt to hash passwords before storing them.

  4. Flask Extensions: Consider using Flask extensions like Flask-SQLAlchemy for database ORM and Flask-Bcrypt for password hashing.

  5. Secure Communication: Ensure all data sent between the client and server is encrypted using HTTPS.

Here's a basic example to illustrate these concepts. This example assumes you're using Flask-SQLAlchemy and Flask-Bcrypt.

First, install the necessary packages:

pip install Flask Flask-SQLAlchemy Flask-Bcrypt 

Then, you can create a simple Flask app like this:

from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt import os app = Flask(__name__) bcrypt = Bcrypt(app) # Configure the SQLAlchemy URI app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///users.db') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) # Define a User model class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) password_hash = db.Column(db.String(120), nullable=False) def set_password(self, password): self.password_hash = bcrypt.generate_password_hash(password).decode('utf-8') def check_password(self, password): return bcrypt.check_password_hash(self.password_hash, password) # Create the database tables @app.before_first_request def create_tables(): db.create_all() # Route to register new users @app.route('/register', methods=['POST']) def register(): username = request.json.get('username') password = request.json.get('password') if not username or not password: return jsonify({"error": "Missing username or password"}), 400 if User.query.filter_by(username=username).first(): return jsonify({"error": "Username already exists"}), 400 new_user = User(username=username) new_user.set_password(password) db.session.add(new_user) db.session.commit() return jsonify({"message": "User created successfully"}), 201 # Route to login users @app.route('/login', methods=['POST']) def login(): username = request.json.get('username') password = request.json.get('password') user = User.query.filter_by(username=username).first() if user and user.check_password(password): return jsonify({"message": "Login successful"}), 200 else: return jsonify({"error": "Invalid username or password"}), 401 if __name__ == '__main__': app.run(debug=True) 

In this example:

  • Usernames and hashed passwords are stored in a database.
  • The bcrypt library is used to hash passwords before they're stored and to check passwords during login.
  • Routes are provided for user registration and login.

Important Security Considerations:

  • Always use HTTPS in production to protect data in transit.
  • Regularly update your dependencies to incorporate security fixes.
  • Follow best practices for database and application security.
  • Be aware of and protect against common web security vulnerabilities (like SQL injection, XSS, CSRF, etc.).

This example is quite basic and does not include features like token-based authentication, session management, input validation, or error handling, which you should consider for a production application.


More Tags

artificial-intelligence reactor-netty string-formatting ios9 pod-install cryptography activator underline shrink derivative

More Programming Guides

Other Guides

More Programming Examples