Skip to content

Instantly share code, notes, and snippets.

@LarsBergqvist
Created September 3, 2016 17:25
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 LarsBergqvist/eee6abf595a2e0a1a0acc6633aa288a0 to your computer and use it in GitHub Desktop.
Save LarsBergqvist/eee6abf595a2e0a1a0acc6633aa288a0 to your computer and use it in GitHub Desktop.
Authorization decorator with Python Flask
def ok_user_and_password(username, password):
return username == app.config['USERNAME'] and password == app.config['PASSWORD']
def authenticate():
message = {'message': "Authenticate."}
resp = jsonify(message)
resp.status_code = 401
resp.headers['WWW-Authenticate'] = 'Basic realm="Main"'
return resp
def requires_authorization(f):
@functools.wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not ok_user_and_password(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment