Using Flask-Login, I want to require login for some views. When I try to access a view that is decorated with @login_required
, I get a 401 message instead of the login page. How do I set this up correctly?
from flask_login import LoginManager, login_required, login_user
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
return User.get(user_id)
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# authenticate user from form
login_user(user)
return redirect(url_for('index'))
return render_template('login.html')
@app.route('/protected')
@login_required
def protected():
return 'Hello, World!'
Flask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code. location parameter is the URL where response should be redirected. statuscode sent to browser's header, defaults to 302.
You haven't told Flask-Login what view to use to show the login form, so it defaults to a generic 401 error. From the docs: "If the login view is not set, it will abort with a 401 error."
login_manager.login_view = 'login'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With