I'm developing a web page using Flask, on an Apache server where the Server is enforcing basic authentication. That is, a user accessing a page on the server is presented with a login screen by Apache, and the login credentials checked prior to passing the request to my page.
The question is whether, and how, I can access the user name from my flask/python code. When using PHP instead of flask/python, on the same server, it is straightforward: The username is a available as a $_SERVER variable (available twice it seems, as the value for keys PHP_AUTH_USER, and also AUTHENTICATE_CN). I'm guessing/hoping that Apache would similarly make the authenticated username available to flask (perhaps through WSGI somehow), but I can't find it.
I've tried displaying all the key/value pairs in request.headers, but the username isn't there. Is there somewhere else I should look?
Apache will use WSGI file to access our Flask application, so the WSGI file allows Apache to interact with Python as if it is native.
I eventually found it, it's available as:
request.environ.get('REMOTE_USER')
Not knowing this wasn't my only problem however, in case it's useful for anyone, here's the story:
Firstly I tried to find out if WSGI was passing the authentication info through to flask. This answer to a different question was very helpful (it shows you how to see everything WSGI is providing before it gets to flask):
https://stackoverflow.com/a/1151129/1956954
When I list the WSGI info as per that answer, it didn't have the user information. But that turned out to be because the setup for apache basic authentication in the relevant sites-enabled apache config file was configured for the document root (a htdocs folder). Since I'm using WSGI to redirect the relevant requests to a folder outside of the document route, I didn't actually have authentication turned on for my page. (And I didn't notice that because I had accessed some pages under htdocs, been forced to authenticate, and assumed that I wasn't being asked to authenticate when I went to my flask pages because the authentication had been cached). Creating another section in the relevant apache sites-enabled file setting up authentication for my flask directories enabled authentication
You can find authentication information in Flask from the request
object.
from flask import request
def 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.
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