How to Create Login in Flask: Simple Step-by-Step Guide
To create a login in
Flask, set up user authentication by verifying credentials, use werkzeug.security to hash passwords, and manage user sessions with Flask-Login or Flask's session. This allows users to securely log in and maintain their login state across pages.Syntax
Here is the basic syntax pattern for creating a login route in Flask:
@app.route('/login', methods=['GET', 'POST']): Defines the login URL and allows form submission.request.form: Accesses submitted form data like username and password.check_password_hash(): Compares stored hashed password with user input.session['user_id'] = user.id: Stores user login state in session.redirect()andurl_for(): Redirect logged-in users to protected pages.
python
from flask import Flask, request, session, redirect, url_for, render_template from werkzeug.security import check_password_hash app = Flask(__name__) app.secret_key = 'your_secret_key' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] user = get_user_by_username(username) # Your user lookup if user and check_password_hash(user.password_hash, password): session['user_id'] = user.id return redirect(url_for('dashboard')) return render_template('login.html')
Example
This example shows a simple Flask app with a login page, password hashing, and session management. It demonstrates how to check user credentials and keep the user logged in.
python
from flask import Flask, request, session, redirect, url_for, render_template_string from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) app.secret_key = 'your_secret_key' # Simulated user database users = { 'alice': generate_password_hash('wonderland123') } @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] password_hash = users.get(username) if password_hash and check_password_hash(password_hash, password): session['user_id'] = username return redirect(url_for('dashboard')) return 'Invalid username or password', 401 return render_template_string(''' <form method="post"> Username: <input name="username"><br> Password: <input name="password" type="password"><br> <input type="submit" value="Login"> </form> ''') @app.route('/dashboard') def dashboard(): if 'user_id' in session: return f'Welcome, {session["user_id"]}! You are logged in.' return redirect(url_for('login')) if __name__ == '__main__': app.run(debug=True)
Output
Running Flask app on http://127.0.0.1:5000/
When visiting /login, user sees a login form.
After successful login, user is redirected to /dashboard with message: "Welcome, alice! You are logged in."
Common Pitfalls
Common mistakes when creating login in Flask include:
- Storing passwords in plain text instead of hashing them.
- Not setting a
secret_keyfor session security. - Failing to check if the user is logged in before showing protected pages.
- Not using POST method for login form submission.
Always hash passwords with werkzeug.security.generate_password_hash and verify with check_password_hash. Use Flask's session to track login state securely.
python
from flask import Flask, request, session from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) app.secret_key = 'secret' # Wrong: storing plain password users = {'bob': 'mypassword'} @app.route('/login', methods=['POST']) def login_wrong(): username = request.form['username'] password = request.form['password'] if users.get(username) == password: # Unsafe plain text check session['user_id'] = username return 'Logged in' return 'Failed', 401 # Right: store hashed password users_hashed = {'bob': generate_password_hash('mypassword')} @app.route('/login_safe', methods=['POST']) def login_right(): username = request.form['username'] password = request.form['password'] pw_hash = users_hashed.get(username) if pw_hash and check_password_hash(pw_hash, password): session['user_id'] = username return 'Logged in safely' return 'Failed', 401
Quick Reference
- @app.route('/login', methods=['GET', 'POST']): Define login URL and allow form submission.
- generate_password_hash(password): Hash passwords before storing.
- check_password_hash(stored_hash, password): Verify password on login.
- session['user_id'] = user_id: Store login state securely.
- redirect(url_for('dashboard')): Redirect after successful login.
- app.secret_key: Must be set for session security.
Key Takeaways
Always hash passwords using werkzeug.security before storing them.
Use Flask's session with a secret key to keep users logged in securely.
Check user credentials on POST login requests and redirect after success.
Protect routes by verifying if the user is logged in via session data.
Avoid storing or comparing plain text passwords to keep data safe.