Reputation: 1106
I am working with google cloud functions in python and I am facing the following difficulties: I don't know how to add a token to the automatically generated endpoint for my HTTP cloud function : Below is the code I deployed :
from flask import Flask, request
from flask_httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()
PROJECT = "projectname"
app = Flask(__name__)
@app.route('/', methods=['PUT', 'POST'])
@auth.login_required
def httpfunction(request):
data = request.stream.read()
return data
The generated URL is :
https://europe-west1-projectname.cloudfunctions.net/httpfunction
I want to add a token to it in order to avoid inappropriate persons to make use it , so basically here I want to avoid POST and PUT requests from unauthorized users. Any ideas how to do this please ?
Upvotes: 0
Views: 452
Reputation: 2319
HTTPBasicAuth
is not using tokens but username and password. To query the endpoint with username and password you should first modify your code to something like this:
from flask import Flask, request
from flask_httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()
users = {
"Obama": "WhiteHouse1",
"Trump": "WhiteHouse2"
}
@auth.get_password
def get_pw(username):
if username in users:
return users.get(username)
return None
app = Flask(__name__)
@app.route('/', methods=['PUT', 'POST'])
@auth.login_required
def httpfunction(request):
data = request.stream.read()
return data
Than you can query the endpoint with providing the username and password. For example a query with cURL
would look like this:
curl -u Trump:WhiteHouse2 -X POST https://europe-west1-projectname.cloudfunctions.net/httpfunction
For queries using tokens, take a look at HTTPTokenAuth
.
Look into the Stack Overflow thread Secure Google Cloud Functions http trigger with auth for other ways of authentication when using Cloud Functions. Implementation is described in Node.js but the idea can be implemented with python as well.
Upvotes: 1