简体   繁体   中英

what is the best way to authenticate to GCP via an HTPP request from an IAP developed with flask and deployed in APP engine?

Could someone help me to deploy a flask IAP on GCP, here is the explanation of my problem.

I want to deploy an IAP I created with flask python on GCP, in my IAP I call a file I stored in google storage. The problem is that when I deploy my IAP to app engine, I can't query it because of authentication.

here is the IAP code.

app = Flask(__name__)
@app.route("/get_result", methods = ['GET', 'POST'])
def get_result():
    r = request
    bucket_name = request.args.get('bucket')
    model_name = request.args.get('model')
    authentification = request.args.get('login')

    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = authentification

    nparr = np.fromstring(r.data, np.uint8)
    # decode image
    image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    images = []
    images.append(image)

    pipeline = load_joblib(bucket_name, model_name)

    pred = pipeline.predict(images)

    return json.dumps({"classe" : pred.tolist()})

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

Here is the code to query my IAP after deployment on GCP

img=cv2.imread('img.jpg')
img = cv2.resize(img, (224, 224), interpolation = cv2.INTER_AREA)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

content_type = 'image/jpeg'
headers = {'content-type': content_type}
# encode image as jpeg
_, img_encoded = cv2.imencode('.jpg', img)
# send http request with image and receive response
url = "https://testapiflask0.ey.r.appspot.com/get_result?bucket=model_test0&model=model.pkl&login=testapiflask0-3fb3109ee673.json"
response = requests.post(url, data=img_encoded.tobytes(), headers=headers)
print(response.text)

Here is the error I got :

'\n<html><head>\n<meta http-equiv="content-type" content="text/html;charset=utf-8">\n<title>500 Server Error</title>\n</head>\n<body text=#000000 bgcolor=#ffffff>\n<h1>Error: Server Error</h1>\n<h2>The server encountered an error and could not complete your request.<p>Please try again in 30 seconds.</h2>\n<h2></h2>\n</body></html>\n'

In my code, I give as a parameter of the http request the path to the JSON file of my service account to authenticate to GCP.

Can someone tell me what is the best way to authenticate to GCP via an http request.

thank you in advance

I assume that as a first step you created a service account for running your code with the necessary permissions.

Then, as explained in the GCP documentation , you may try providing the credentials file to the Cloud Storage client:

def explicit():
    from google.cloud import storage

    # Explicitly use service account credentials by specifying the private key
    # file.
    # In your case:
    authentification = request.args.get('login')

    # storage_client = storage.Client.from_service_account_json(
    #    'service_account.json')
    storage_client = storage.Client.from_service_account_json(
        authentification)

    # Make an authenticated API request
    buckets = list(storage_client.list_buckets())
    print(buckets)

Having said that, please, take into consideration that passing credentials related information in this way is unrecommended, a security risk, and a bad practice.

Instead, as you are running your application in App Engine, you can use the builtin security mechanisms provided by GCP and use either the default service account or anuser provided one and grant that service account the necessary permissions to interact with your services, Cloud Storage in this case; using this implicit credentials will be a very more secure solution and your code, simpler:

def implicit():
    from google.cloud import storage

    # If you don't specify credentials when constructing the client, the
    # client library will look for credentials in the environment.
    storage_client = storage.Client()

    # Make an authenticated API request
    buckets = list(storage_client.list_buckets())
    print(buckets)

As you can see, there is not any reference to security credentials, all is handled behind the scenes by GCP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM