Created
September 26, 2016 15:38
-
-
Save nickstenning/c1bab3b0031e62fae6c7e3346ccb293d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
import os | |
from flask import Flask, Response | |
from flask import abort, request | |
app = Flask(__name__) | |
@app.route("/") | |
@app.route("/headers") | |
def basic_auth(): | |
if 'authorization' in request.headers: | |
authdata = parse_authdata(request.headers['authorization']) | |
else: | |
abort(401) | |
return Response('authdata = {!r}\n'.format(authdata), | |
mimetype='text/plain') | |
@app.errorhandler(401) | |
def custom_401(error): | |
return Response('Access denied', 401, {'www-authenticate':'Basic realm="Test realm"'}) | |
def parse_authdata(value): | |
try: | |
auth_type, auth_info = value.split(None, 1) | |
auth_type = auth_type.lower() | |
except ValueError: | |
return | |
if auth_type != 'basic': | |
return | |
return base64.standard_b64decode(auth_info) | |
if __name__ == "__main__": | |
port = int(os.environ.get('PORT', 5000)) | |
app.run(host='0.0.0.0', port=port) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment