0
0
Flaskframework~5 mins

Login_required decorator in Flask

Choose your learning style9 modes available
Introduction

The login_required decorator makes sure only logged-in users can see certain pages. It helps keep parts of your website private.

When you want to protect a user profile page so only the owner can see it.
When you have a dashboard that should only be visible after logging in.
When you want to stop visitors from accessing settings or admin pages without logging in.
When you want to redirect users to the login page if they try to visit protected pages.
When you want to keep user data safe by restricting access.
Syntax
Flask
@login_required
def your_view_function():
    # code for the view
    return something

Place @login_required right above the view function you want to protect.

This decorator is provided by Flask-Login extension, so you need to install and set up Flask-Login first.

Examples
This protects the dashboard page so only logged-in users can access it.
Flask
@login_required
def dashboard():
    return 'Welcome to your dashboard!'
Here, the profile route is protected by login_required.
Flask
@app.route('/profile')
@login_required
def profile():
    return 'User profile page'
Sample Program

This Flask app uses Flask-Login to protect the /protected page. You must visit /login first to log in. Then you can access /protected. The login_required decorator blocks access to /protected and /logout if not logged in.

Flask
from flask import Flask, redirect, url_for
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user

app = Flask(__name__)
app.secret_key = 'secret-key'

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

class User(UserMixin):
    def __init__(self, id):
        self.id = id

users = {'user1': User('user1')}

@login_manager.user_loader
def load_user(user_id):
    return users.get(user_id)

@app.route('/login')
def login():
    user = users['user1']
    login_user(user)
    return 'Logged in! Go to /protected'

@app.route('/protected')
@login_required
def protected():
    return f'Hello, {current_user.id}! This page is protected.'

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return 'Logged out!'

if __name__ == '__main__':
    app.run(debug=False)
OutputSuccess
Important Notes

Remember to set login_manager.login_view to the login route so users get redirected properly.

If a user is not logged in and tries to access a protected page, they will be sent to the login page automatically.

You need to create a user loader function to tell Flask-Login how to find users.

Summary

login_required keeps pages safe by allowing only logged-in users.

Use it by placing @login_required above your view functions.

It works with Flask-Login and redirects users to login if they are not authenticated.