Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-Login shows 401 instead of redirecting to login view

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!'
like image 645
Adnan Avatar asked Nov 15 '15 19:11

Adnan


People also ask

How do I redirect a link in Flask?

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.


1 Answers

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'
like image 79
davidism Avatar answered Oct 20 '22 16:10

davidism