Reputation: 1287
I designed a simple Django service which communicates with a Flask microservice using POST Requests. Basically, the user submits a form with some preferences, those preferences are sent to a Django view, the Django view will send those to Flask, which will perform some operations according to those preferences and then return a response to Django, which will show it to the user or do some other operations.
This whole system works for now, the only problem is that i don't know how safe it is. Here is how i'm sending the request:
def myview(request):
# Some code ...
req = requests.post('http://127.0.0.1:5000', json=myDataDict)
And here is how my Flask service receives it:
@app.route("/", methods=["GET", "POST"])
def receivePost():
data = request.get_json()
# some code ..
return jsonify(data)
Again, this system works locally; i want to make it safer for when i'll deploy it.
Here are my concerns:
1) What if a third party reads what's inside the variable myDataDict
when the two services are communicating?
2) The Flask service should accept requests ONLY from the Django service.
I made some research and found about libraries such as OAuth2, and a token authentication system would be a good way to make this system safer, but i don't really know how to add it to my actual code. So here is my question: how can i make this system safe? Any kind of advice is appreciated.
Upvotes: 0
Views: 453
Reputation: 709
You can use Flask-login
to authenticate users using an API
key and IP
address. Here is an example.
@login_manager.request_loader
def load_user_from_request(request):
api_key = request.headers.get('My-Api-Key')
is_api_path = re.match(r"^/api/+", request.path)
if is_api_path and api_key:
user = User.query.filter_by(key=api_key).first()
if user and user.ip == request.remote_addr:
return user
return None
Using Flask-login
's request_loader
to load and authenticate users without using cookies.
First get the API
key from HTTP
header called My-Api-Key
here. Then check that the request URL
contains /api/
to narrow where you can authenticate with API
.
If the user is found check that the request is coming from their IP
.
Inside your Django
application you can request FLASK
application like this.
resp = requests.post(url + "/api/myendpoint", json=data, headers={'Content-Type': 'application/json', 'My-Api-Key': api_key})
Finally don't forget to use HTTPS
Upvotes: 1