Tuesday, January 15, 2019

Authentication

DEF

Library
=====================================================
There is a small Flask extension that can help with this, written by no other than yours truly. So let's go ahead and install Flask-HTTPAuth:
$ flask/bin/pip install flask-httpauth
=====================================================


CODE
=====================================================
from flask import Flask, jsonify
from flask import make_response
from flask_httpauth import HTTPBasicAuth


app = Flask(__name__)

auth = HTTPBasicAuth()

@app.route("/<string:username>",  methods=['GET'])
def get_auth(username):
    return get_password(username)

@auth.get_password
def get_password(username):
    if username == 'divakar':
        return 'python'
    return unauthorized()

#    return None   ------you can use this instead of return unauthorized()

@auth.error_handler
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized access'}), 401)

if __name__ == '__main__':
    app.run(debug=True)

=====================================================


REQUEST & RESPONSE
=====================================================

=====================================================


DETAIL-

The get_password function is a callback function that the extension will use to obtain the password for a given user. In a more complex system this function could check a user database, but in this case we just have a single user so there is no need for that.
The error_handler callback will be used by the extension when it needs to send the unauthorized error code back to the client. Like we did with other error codes, here we customize the response so that is contains JSON instead of HTML.
With the authentication system setup, all that is left is to indicate which functions need to be protected, by adding the @auth.login_required decorator. For example:
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
@auth.login_required
def get_tasks():
    return jsonify({'tasks': tasks})

22

No comments:

Post a Comment