User Authentication in Flask: 3 Practical Examples

Discover 3 practical examples for implementing user authentication in Flask, perfect for beginners and developers alike.
By Taylor

Introduction to User Authentication in Flask

User authentication is a crucial aspect of web development, allowing you to manage user access and protect sensitive information. Flask, a lightweight web framework for Python, provides several ways to implement authentication. In this article, we’ll walk through three diverse examples of implementing user authentication in Flask to help you get started.

Example 1: Basic User Authentication with Flask-Login

Context

This example demonstrates how to set up a simple user authentication system using Flask-Login, a popular extension that makes it easy to manage user sessions.

from flask import Flask, render_template, redirect, url_for, request, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'

db = SQLAlchemy(app)
login_manager = LoginManager(app)

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(150), unique=True, nullable=False)
    password = db.Column(db.String(150), nullable=False)

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=username).first()
        if user and user.password == password:
            login_user(user)
            return redirect(url_for('dashboard'))
        flash('Invalid credentials')
    return render_template('login.html')

@app.route('/dashboard')
@login_required
def dashboard():
    return f'Hello, {current_user.username}!'

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)

Notes

  • Make sure to create a login form in login.html that collects the username and password.
  • For production, consider using a hashing library like bcrypt for password storage.

Example 2: OAuth2 Authentication with Flask-Dance

Context

In this example, we’ll implement user authentication using OAuth2 with Flask-Dance, which allows users to sign in with their Google accounts.

```python
from flask import Flask, redirect, url_for from flask_dance.contrib.google import make_google_blueprint, google
from flask_dance import run

app = Flask(__name__)
app.secret_key = ‘your_secret_key’

google_bp = make_google_blueprint(client_id=’your_client_id’, client_secret=’your_client_secret’, redirect_to=’google_login’) app.register_blueprint(google_bp, url_prefix=’/google_login’)

@app.route(’/’)
def index():
return ‘Welcome! Login with Google

@app.route(’/google_login’) def google_login():
if not google.authorized:
return redirect(url_for(’google.login’))
resp = google.get(’/plus/v1/people/me’)
assert resp.ok, resp.text
return f’You are logged in as: {resp.json()[