How do I secure a flask api?

Issue

My goal is to secure an api through token based authentication on aws beanstalk. Im using flask as a framework. To use the API, the user should only need the url and a token.

I really want to keep it as simple as possible but also secure.

My approach:

from flask import Flask, jsonify, request

app = Flask(__name__)


@app.route('/test', methods=['GET'])
def get_tasks():
    headers = request.headers
    auth = headers.get("auth")
    if auth == lookupTokenInDatabase():
        return jsonify({"message": "OK: Authorized"}), 200

    else:
        return jsonify({"message": "ERROR: Unauthorized"}), 401


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

The client request would look like this:

import requests

url = "test"

payload = {}
headers = {'auth':'token'}

response = requests.request("GET", url, headers=headers, data = payload)

print(response)

I am aware that this is probably not state of the art, but does it provide at least some type of security?

Solution

Id use something like Flask-JWT-extended , you can generate "api tokens" that would be valid for x/y amount of time once user logs in use flask to send jwt token and save it inside of cookie. After that set up your front end to send the "bearer token" on each request so you could validate the user on back-end.

Answered By – dariokl

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published