Reading IIS Session Variables from Flask App with wfastcgi.py
I'm building a secured app with Flask 0.12 on IIS 7.0. The site is on a subdomain so its urls all begin with:
https://<subdomain>.<domain>/<app_name>/
wfastcgi.py
strips away these prefixes and passes only the route names to my Flask app. So the above URL would be presented to my app as route /
. There are other web apps (ASP.net and PHP) hosted on the same subdomain but with different app_name
constants.
Since my users are required to login to the server before hitting my app, I'd like to use their Windows domain unique user ids to manage page-by-page permissions in the app. In ASP.NET I could do this using the httpcontext
but that isn't available in Flask. And when I dump the session contents like so:
@app.route('/session_tester')
def session_test():
return str(session)
I get an empty page in response.
How can I access my IIS session variables from the Flask App? Is there a configuration variable I'm missing?
When a user is authenticated by IIS, their username is present in the REMOTE_USER
environment variable. Other contextual information is also stored in different environment variables. You can configure which variables are made available to the application, but REMOTE_USER
and a few others should be there by default.
So, you should be able to get the logged in user by os.environ.get('REMOTE_USER')
.
@app.route('/')
def index():
username = os.environ.get('REMOTE_USER')
template = "<h1>User: {{ username }}</h1>"
return render_template_string(template, username=username)
If you want your Flask session to be aware of the user session, you need to have users log into the Flask app, not IIS. Alternatively, you can have a middleware that logs users into your Flask app based on the REMOTE_USER
environment variable. This should be achievable using the flask_login
extension, for example.
Edit:
You can also access environment variables via the request
proxy object. e.g. request.environ['REMOTE_USER']
. See also request.authorization