Skip to content

Instantly share code, notes, and snippets.

@gnilchee
Created October 11, 2016 06:40
Show Gist options
  • Save gnilchee/8154b64b7390a55e0656b524ae53f40d to your computer and use it in GitHub Desktop.
Save gnilchee/8154b64b7390a55e0656b524ae53f40d to your computer and use it in GitHub Desktop.
flask simple auth
#!/usr/bin/env python3
from functools import wraps
from flask import Flask, request, Response, jsonify
app = Flask(__name__)
def check_auth(username, password):
return username == 'admin' and password == 'sECreTpassW0Rd'
def authenticate():
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
@app.route("/")
def hello():
return jsonify({'Hello World': 'true'}), 200
@app.route("/secret")
@requires_auth
def private_page():
return jsonify({'private': 'true'}), 200
if __name__ == "__main__":
app.run(host='0.0.0.0')
@gnilchee
Copy link
Author

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