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"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_viewlogin_view
Configure login_view
login_manager.login_view = "login"login_manager.login_view = "login"Now anonymous users are redirected to /login/login.
The “next” parameter
Flask-Login often preserves the originally requested URL via a nextnext parameter.
Your login view can redirect back to it after successful login.
Be careful:
- validate
nextnextis a safe local URL (avoid open redirects)
current_user
Inside protected routes, you can use:
from flask_login import current_user
current_user.id
current_user.is_authenticatedfrom flask_login import current_user
current_user.id
current_user.is_authenticatedThis is how you tailor pages to the logged-in user.
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
