I'm using Flask-HTTPAuth to handle authentication in my app. I have a lot of views, and I don't want to add login_required
to every one of them. How can I make login required by default?
from flask.ext.httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()
@auth.verify_password
def verify_password(username, password):
return username == '111' and password == '222'
@app.route('/')
@app.route('/home/')
@auth.login_required
def index():
return 'Hello'
@app.route('/route2/')
def route2():
return 'route2'
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
You can add a
before_request
function to require login by default, and create a simplelogin_exempt
decorator for the few routes that don't require it.Make sure to exempt static files, otherwise they won't load for unauthenticated users.
Flask-HTTPAuth's
login_required
doesn't have a way to separate the require logic from the view decorator, you need to go through a little dance to require auth without running a view.