How to access Apache Basic Authentication user in Flask How to access Apache Basic Authentication user in Flask flask flask

How to access Apache Basic Authentication user in Flask


You can find authentication information in Flask from the request object.

from flask import requestdef my_view():    auth = request.authentication    username = auth.username    password = auth.password    ...

Note however that if you're using apache mod_wsgi, you'll need to turn on the WSGIPassAuthorization directive in your virtualhost config. Otherwise apache will consume the authentication header and won't pass it to the WSGI layers.

<virtualhost *:443>    ...    WSGIPassAuthorization On    ...</virtualhost>

more info here and here.


I eventually found it, it's available as:

request.environ.get('REMOTE_USER')

Not knowing this wasn't my only problem however, in caseit's useful for anyone, here's the story:

Firstly I tried to find out if WSGI was passing the authenticationinfo through to flask. This answer to a different question was veryhelpful (it shows you how to see everything WSGI is providing beforeit gets to flask):

https://stackoverflow.com/a/1151129/1956954

When I list the WSGI info as per that answer, it didn't have theuser information. But that turned out to be because the setup forapache basic authentication in the relevant sites-enabled apacheconfig file was configured for the document root (a htdocs folder).Since I'm using WSGI to redirect the relevant requests to a folderoutside of the document route, I didn't actually have authenticationturned on for my page. (And I didn't notice that because I had accessedsome pages under htdocs, been forced to authenticate, and assumed thatI wasn't being asked to authenticate when I went to my flask pagesbecause the authentication had been cached).Creating another section in the relevant apache sites-enabledfile setting up authentication for my flask directories enabled authentication