Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

How do I secure a flask api?

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...