简体   繁体   中英

login_required decorator not redirecting to correct endpoint

Using Flask-security extension, I was trying to protect some views, for example:

from flask_security import login_required

@auth.route('/signin', methods=['GET', 'POST'])
def signin():
    #...

#...

@auth.route('/change-password', methods=['GET', 'POST'])
@login_required
def change_password():
    #...

With the following config.py for Flask-Security:

SECURITY_URL_PREFIX = '/auth'
SECURITY_LOGOUT_URL = '/signout'
SECURITY_UNAUTHORIZED_VIEW = '/signin'

And yet, when I try to access a protected view, I get the following werkzeug.routing.BuildError message:

werkzeug.routing.BuildError: Could not build url for endpoint 'auth.login'.
Did you mean 'auth.signin' instead?

What could be the reason behind this error?

Flask-security uses Flask-login's login_required decorator and as per documentation :

flask_login.login_required(func)

If you decorate a view with this, it will ensure that the current user is logged in and authenticated before calling the actual view. (If they are not, it calls the LoginManager.unauthorized callback .)

While one can use LoginManager.unauthorized callback to setup a response:

unauthorized_handler(callback)

This will set the callback for the unauthorized method, which among other things is used by login_required . It takes no arguments, and should return a response to be sent to the user instead of their normal view.

So, I ended up defining the callback myself:

 @app.login_manager.unauthorized_handler
 def unauth_handler():
      if request.is_xhr:
          return jsonify(success=False,
                         data={'login_required': True},
                         message='Authorize please to access this page.'), 401
      else:
          return redirect(url_for('auth.signin'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM