5

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!

kramer65
  • 50,427
  • 120
  • 308
  • 488

1 Answers1

5

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/

Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43
  • Very good point. I'm a newby to Apache server administration so please bear with me. I searched the file `/etc/apache2/apache2.conf` for `WSGIPassAuthorization` but it isn't currently in the file. Do I just need to add it to the file at the bottom and restart Apache, or do I need to set that somewhere else? – kramer65 Jul 22 '15 at 12:54
  • It depends on your configuration, but I think yes, you could add this directive at the bottom: http://stackoverflow.com/questions/9780966/where-do-i-put-wsgipassauthorization-on – Eugene Soldatov Jul 22 '15 at 13:01
  • In the end I put it in my website's apache config file which I've got in `/etc/apache2/sites-available/mysite.com.conf`. It works perfectly fine now. Thanks a million! – kramer65 Jul 22 '15 at 13:54