Protecting Routes (@login_required)
To protect a route so only logged-in users can access it:
from flask_login import login_required
@app.route("/dashboard")
@login_required
def dashboard():
return "Secret dashboard"If a user is not logged in, Flask-Login will:
- redirect them to
login_view
flowchart TD
A["request for a protected route"] --> B["@login_required runs first"]
B --> C{"current_user.is_authenticated?"}
C -->|yes| D["your view function runs"]
C -->|no| E["save the target in the 'next' parameter"]
E --> F["redirect to login_view"]
F --> G["user logs in"]
G --> H{"is 'next' a safe local URL?"}
H -->|yes| I["redirect back to where they were going"]
H -->|no| J["redirect to a known-safe default"]
Configure login_view
Section titled “Configure login_view”login_manager.login_view = "login"Now anonymous users are redirected to /login.
The “next” parameter
Section titled “The “next” parameter”Flask-Login often preserves the originally requested URL via a next parameter.
Your login view can redirect back to it after successful login.
Be careful:
- validate
nextis a safe local URL (avoid open redirects)
current_user
Section titled “current_user”Inside protected routes, you can use:
from flask_login import current_user
current_user.id
current_user.is_authenticatedThis is how you tailor pages to the logged-in user.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading