Skip to content

Instantly share code, notes, and snippets.

@nexus166
Created March 18, 2019 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nexus166/f5e9f9b1b72e1d288b1855b3eacea6b5 to your computer and use it in GitHub Desktop.
Save nexus166/f5e9f9b1b72e1d288b1855b3eacea6b5 to your computer and use it in GitHub Desktop.
delegate BasicAuth to a Vault instance (ngx_http_auth_request_module)
import os
import hvac
import json
from flask import Flask, request, make_response
app = Flask(__name__, template_folder='templates')
app.config['SECRET_KEY'] = 'https:/your.vault.instance:8200/'
app.config['FLASK_ENV'] = 'production'
VAULT_ADDR = os.environ['VAULT_ADDR']
@app.route('/')
def index():
if request.authorization:
auth = request.authorization
client_IP = ''
if 'Cf-Connecting-Ip' in request.headers:
client_IP = request.headers['Cf-Connecting-Ip']
else:
client_IP = request.headers['X-Real-Ip']
try:
vc = hvac.Client(url=VAULT_ADDR, token=auth.password)
assert vc.is_authenticated()
print('LOGIN OK FROM [' + client_IP + '] : [' + auth.username + ']'), 200
return make_response('LOGIN OK', 200), 200
except:
print('INVALID PASSWORD FROM [' + client_IP + '] : [' + auth.username + ':' + auth.password + ']'), 523
pass
return make_response('LOGIN FAILED', 401, {'WWW-Authenticate' : 'Basic realm="vault login required"'}), 401
if __name__ == '__main__':
app.run(debug=True)
@nexus166
Copy link
Author

note: the Cf-Connecting-Ip header and HTTP 523 are just for Cloudflare

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment