I'm building a website with Flask, in which I now want to protect an admin view with a very simple authentication mechanism. For this I wrote the following wrapper code:
def check_auth(username, password):
current_app.logger.error('Log from check_auth')
return username == 'myusername' and password == 'mypassword'
def authenticate():
current_app.logger.error('Log from authenticate function')
return Response('Bad luck my friend.', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
current_app.logger.error('Log from requires_auth function')
auth = request.authorization
current_app.logger.error(auth) # <= HERE I LOG auth
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
@requires_auth
def some_view():
return 'some stuff'
This works fine when using the Flask development server. I just deployed this on Apache/mod_wsgi, but unfortunately now it doesn't work; after filling in my login details it simply reloads the login screen (suggesting the password is wrong).
I put some logging in there, and it now logs the following:
Log from requires_auth function
None
Log from authenticate function
So as you can see, auth
(which should contain the filled in username and password) remains None. The weird thing is that these three logs already display as soon as the login screen is displayed. This means that instead of waiting for the user to fill in his username and password, the function continues to execute.
Does anybody know what I'm doing wrong here? And why does it work with the Flask development server, but doesn't it work with Apache/mod_wsgi? All tips are welcome!
A common way of deploying a Flask web application in a production environment is to use an Apache server with the mod_wsgi module, which allows Apache to host any application that supports Python's Web Server Gateway Interface (WSGI), making it quick and easy to get an application up and running.
I think this would be helpful:
If you are using basic auth with mod_wsgi you will have to enable auth forwarding, otherwise apache consumes the required headers and does not send it to your application: WSGIPassAuthorization.
http://flask.pocoo.org/snippets/8/
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