云中的安全api使用云端点espv2 beta运行云功能和应用程序引擎
介紹 (Introduction)
Just as organisations need services management for microservices, they need API management for their APIs.
正如組織需要微服務的服務管理一樣,他們也需要其API的API管理。
With serverless services like Cloud Run, Cloud Functions and App Engine, it is very easy and quick to create APIs. However, Security, Monitoring, Publishing APIs are some of the major challenges.
借助Cloud Run,Cloud Functions和App Engine等無服務器服務, 創建API非常簡單快捷。 但是,安全,監視和發布API是一些主要挑戰。
In this blog, we will see how to secure API’s in Cloud Run, Cloud Functions and App Engine Standard environment using API Keys and Bearer Token.
在此博客中,我們將了解如何使用API??密鑰和Bearer令牌在Cloud Run,Cloud Functions和App Engine Standard環境中保護API。
什么是云端點? (What is Cloud Endpoints?)
Cloud Endpoints is a distributed API management system. It provides an API console, hosting, logging, monitoring and other features to help you to create, share, maintain and secure APIs.
Cloud Endpoints是一個分布式API管理系統。 它提供API控制臺,托管,日志記錄,監視和其他功能,以幫助您創建,共享,維護和保護API。
ESPv2 Beta
ESPv2 Beta
There are two versions of Extensible Service Proxy (ESP).ESPv1 is an Nginx-based proxy that is modified to be highly-scalable and to work as a Google product. ESPv2 is an Envoy-based, highly scalable product that promises to have a small footprint on your infrastructure.
有兩種版本的可擴展服務代理(ESP)。ESPv1是基于Nginx的代理,已對其進行了修改,使其具有很高的可擴展性并可以用作Google產品。 ESPv2是基于Envoy的 ,高度可擴展的產品,有望在您的基礎結構中占用很小的空間。
See architecture documentation for Cloud Endpoints.
請參閱云端點的體系結構文檔 。
我們會做什么 (What we’ll be doing)
- Deploy services on Cloud Run, Cloud Functions, App Engine in Python3, using Flask. These will be in private mode. 使用Flask在Python3中的Cloud Run,Cloud Functions,App Engine上部署服務。 這些將處于私有模式。
- Deploy Endpoint ESPv2 Beta container on Cloud Run. 在Cloud Run上部署Endpoint ESPv2 Beta容器。
- Invoke services using API Key 使用API??密鑰調用服務
- Use server-to-server (JWT) authentication. 使用服務器到服務器(JWT)身份驗證。
- Use Quota to limit API usage 使用配額限制API使用
- Track API activity. 跟蹤API活動。
建筑 (Architecture)
We are aiming to create an app with 3 different services using following components.
我們旨在使用以下組件來創建具有3種不同服務的應用程序。
All required files are stored here.
所有必需的文件都存儲在這里 。
部署安全服務 (Deploy the secured services)
建立 (Setup)
In order to complete this guide, you’ll need to install the following tools
為了完成本指南,您需要安裝以下工具
Git: Git is used to clone the example code and trigger new deployments.
Git :Git用于克隆示例代碼并觸發新的部署。
GCP: You will need a GCP account with billing enabled.
GCP :您需要一個啟用了結算功能的GCP帳戶。
- Python 3.7 : Python is installed to run a script. Python 3.7:已安裝Python以運行腳本。
創建GCP項目 (Create GCP Project)
Create a GCP project for this tutorial.
為此教程創建一個GCP項目。
Select Firestore mode
選擇Firestore模式
- Go to Firestore 前往消防站
- Select Native Mode 選擇純模式
- Select a Location (e.g. United States) 選擇一個位置(例如美國)
- Click on “Create Database” 點擊“創建數據庫”
Enable APIs
啟用API
Go to APIs & Services and Enable Following APIs
轉到API和服務并啟用以下API
- Cloud Build 云構建
- Cloud Run 云跑
- Identity-Aware Proxy 身份識別代理
- Service Control API 服務控制API
Create Service Account
創建服務帳號
Create a service account to be used in Authorization Bearer section and download key.
創建要在“授權承載”部分中使用的服務帳戶并下載密鑰。
Clone the Repository
克隆存儲庫
Open Cloud Shell, Clone the following repository containing the sample code, then switch to the cloud-run directory:
打開Cloud Shell,克隆以下包含示例代碼的存儲庫,然后切換到cloud-run目錄:
$ export PROJECT_ID = <PROJECT_ID>$ export PROJECT_NUMBER = <PROJECT_NUMBER>$ git clone https://github.com/vikramshinde12/endpoints-espv2.git$ cd endpoints-espv2/cloud-run
云跑 (Cloud Run)
The code to add an employee in the Firestore.
在Firestore中添加員工的代碼。
import os from flask import Flask, request from google.cloud import firestoreapp = Flask(__name__)@app.route('/employee', methods=['POST', 'PUT']) def add_update_employee():json_ = request.get_json()if 'id' not in json_:return 'Precondition Failed', 412client = firestore.Client()doc_ref = client.collection(u'employee').document(u'{}'.format(json_.get('id')))doc_ref.set(json_)return 'Created', 201if __name__ == '__main__':app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))The Dockerfile of the image
映像的Dockerfile
FROM python:3.7 WORKDIR / COPY requirements.txt /requirements.txt RUN pip3 install -r requirements.txt COPY . / CMD ["python3", "api.py"]First build the image.
首先建立映像。
$ gcloud builds submit --tag gcr.io/$PROJECT_ID/endpoint-espv2Then, deploy the container in private mode
然后,以私有模式部署容器
$ gcloud run deploy employee --no-allow-unauthenticated \--image gcr.io/$PROJECT_ID/endpoint-espv2 \
--region us-central1 --platform managed
云功能 (Cloud Functions)
The code to get the employee from the Firestore.
從Firestore獲取員工的代碼。
from flask import jsonify from google.cloud import firestoredef get_emp(request):try:if request.args and 'employee_id' in request.args:employee_id = request.args.get('employee_id')else:return 'Precondition Failed', 412client = firestore.Client()doc_ref = client.collection(u'employee').document(u'{}'.format(employee_id))doc = doc_ref.get()if doc.to_dict():response = jsonify(doc.to_dict())response.status_code = 200else:response = jsonify({'httpResponseCode': '404','errorMessage': 'Employee does not exist'})response.status_code = 404return responseexcept Exception as e:return eDeploy the Cloud Function in private mode.
在私有模式下部署云功能。
$ cd ..$ gcloud functions deploy employee --trigger-http \
--runtime python37 --source cloud-function --entry-point get_emp \
--region us-central1 --no-allow-unauthenticated
Google App Engine(標準 ) (Google App Engine (Standard))
The code to Delete the employee from theFirestore
從Firestore中刪除員工的代碼
import os from flask import Flask from google.cloud import firestoreapp = Flask(__name__)@app.route('/employee/<employee_id>', methods=['DELETE']) def delete_employee(employee_id):client = firestore.Client()doc_ref = client.collection(u'employee').document(u'{}'.format(employee_id))if not doc_ref.get().to_dict():return 'Not Found', 404else:doc_ref.delete()return 'OK', 200if __name__ == '__main__':app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))There are 2 steps involved:
涉及兩個步驟:
2. Configure IAP.
2.配置IAP。
The App Engine is public by default, activate IAP on App Engine.
默認情況下,App Engine是公共的,請在App Engine上激活IAP。
Go to App Engine →Settings → Identity-Aware Proxy → Configure Now.
轉到App Engine→設置→身份識別代理→現在配置。
Give permission “IAP-secured Web App User” to the service account <PROJECT-NUMBER>-compute@developer.gserviceaccount.com
向服務帳戶<PROJECT-NUMBER> -compute@developer.gserviceaccount.com授予“受IAP保護的Web應用程序用戶”權限
This is important so that App Engine will be accessible by the Cloud Endpoints service that we will be deploying in next step.
這一點很重要,以便我們將在下一步中部署的Cloud Endpoints服務可以訪問App Engine。
云端點(ESPv2) (Cloud Endpoints (ESPv2))
Now, we have deployed backend services in Cloud Run, Cloud Functions and App Engine in private mode, we can start to frontend them using proxy service in Cloud Endpoints ESPv2 Beta.
現在,我們已經在私有模式下的Cloud Run,Cloud Functions和App Engine中部署了后端服務,我們可以開始使用Cloud Endpoints ESPv2 Beta中的代理服務來對它們進行前端處理。
Following steps are involved
涉及以下步驟
部署ESPv2默認Docker映像 (Deploy an ESPv2 default Docker image)
As part of the OpenAPI definition, we need to obtain a valid hostname of the gateway service that will front all requests to our API services. We can only obtain a valid hostname for our proxy once we’ve deployed something to Cloud Run. To achieve this, we’ll deploy the default ESPv2 Docker image.
作為OpenAPI定義的一部分,我們需要獲取網關服務的有效主機名,該主機名會將所有請求發送到我們的API服務。 將某些內容部署到Cloud Run后,我們才能為代理獲取有效的主機名。 為此,我們將部署默認的ESPv2 Docker鏡像。
$ gcloud run deploy gateway \--image="gcr.io/endpoints-release/endpoints-runtime-serverless:2" \
--allow-unauthenticated \
--region us-central1 \
--platform managed
I gave CLOUD_RUN_SERVICE_NAME as gateway
我給CLOUD_RUN_SERVICE_NAME作為gateway
If you notice from the gcloud command, we won’t be blocking any traffic by default. The proxy service itself will do that for us.
如果您從gcloud命令中注意到,則默認情況下我們不會阻止任何流量。 代理服務本身將為我們做到這一點。
Once the proxy service has deployed, take note of the hostname, we’ll use this in the OpenAPI definition.
部署代理服務后,請記下主機名,我們將在OpenAPI定義中使用它。
創建一個OpenAPI定義 (Create an OpenAPI definition)
Now, we have to declare to Cloud Endpoint service where and how to reach the backend services.
現在,我們必須向Cloud Endpoint服務聲明在何處以及如何到達后端服務。
You must have an OpenAPI document based on OpenAPI specification. Let’s create one for our Employee API.
您必須具有基于OpenAPI規范的OpenAPI文檔。 讓我們為Employee API創建一個。
Create a YAML file called openapi-defination.yaml.let’s start with header
創建一個名為openapi-defination.yaml的YAML文件。
Header
標頭
swagger: '2.0'info:
title: Employee API
description: Employee API on Cloud Endpoints with a Cloud Run, Cloud Function and App Engine with IAP backend
version: 1.0.0
host: gateway-<hash>-uc.a.run.app
schemes:
- https
The host is the hostname of the proxy or gateway when we deployed ESPv2 default Docker image.
host是我們部署ESPv2默認Docker映像時的代理或網關的主機名。
The title is the name of the API in the API & Services section.
title是“ API和服務”部分中API的名稱。
Paths
路徑
Add following paths in the openapi-defination.yaml file.
在openapi-defination.yaml文件中添加以下路徑。
x-google-backend address: This is the full URL of the python services deployed earlier. (change <PROJECT_ID> with your project ID)
x-google-backend address :這是先前部署的python服務的完整URL。 (將<PROJECT_ID>更改為您的項目ID)
Cloud Functions
云功能
GET employee endpoint: This is endpoint receives employee_id in path parameter.
GET員工端點:這是端點在path參數中接收的employee_id。
/employee/{employee_id}:get:
summary: Get an Employee
operationId: getEmployee
x-google-backend:
address: https://us-central1-<PROJECT_ID>.cloudfunctions.net/employeeprotocol: h2
parameters:
- name: employee_id
in: path
Cloud Run
云跑
This POST endpoint add/update employee in Firestore. It is recommend to use the APPEND_PATH_TO_ADDRESS for host_rewriting.
此POST端點在Firestore中添加/更新員工。 建議使用APPEND_PATH_TO_ADDRESS進行host_rewrite。
/employee:post:
summary: Add Employee using Cloud Run Service
operationId: add_update_employee
x-google-backend:
address: https://employee-<hash>-uc.a.run.apppath_translation: APPEND_PATH_TO_ADDRESS
parameters:
- name: employee
in: body
description: Employee to be Added
schema:
$ref: '#/definitions/Employee'
The Schema definition of the employee
員工的架構定義
definitions:Employee:
type: object
required:
- id
- firstname
- lastname
properties:
id:
type: string
firstname:
type: string
lastname:
type: string
App Engine
應用引擎
The DELETE endpoint to delete an employee from the firestore.
DELETE端點,用于從Firestore中刪除員工。
delete:summary: Delete Employee using Google App Engine service.
operationId: deleteEmployee
x-google-backend:
address: https://<PROJECT_ID>.appspot.com path_translation: APPEND_PATH_TO_ADDRESS
jwt_audience: <PROJECT_NUMBER>-<HASH>.apps.googleusercontent.com
protocol: h2
parameters:
- name: employee_id
in: path
In addition to x-google-backend address, IAP also check the correct audience of the JWT token. The jwt_audience is the IAP client ID. Get the Client ID from APIs & Services → Credentials → OAuth 2.0 client IDs →IAP-App-Engine-app
除了x-google-backend地址外,IAP還檢查JWT令牌的正確受眾。 jwt_audience是IAP客戶端ID 。 從API和服務→憑據→OAuth 2.0客戶端ID→IAP-App-Engine-app獲取客戶端ID
Add Authentication (API Keys)
添加身份驗證(API密鑰)
There are multiple ways to add security, let’s start with API Key.
有多種增加安全性的方法,讓我們從API密鑰開始。
Add API key security in each paths
在每個路徑中添加API密鑰安全性
security:- api_key: []
And add the security definition at the end of the file
并在文件末尾添加安全定義
securityDefinitions: api_key:type: "apiKey"
name: "key"
in: "query"
部署OpenAPI定義 (Deploy the OpenAPI definition)
Now we have created the OpenAPI definition for the route in our service we need to deploy it to Cloud Endpoints.
現在,我們已經在服務中為路由創建了OpenAPI定義,我們需要將其部署到Cloud Endpoints。
gcloud endpoints services deploy openapi-definition.yamlWhen the deployment is successful, please note the CONFIG_ID in the response. It’ll follow the naming convention [YYYY-MM-DDrx] = [2020–01–01r0].
部署成功后,請在響應中記下CONFIG_ID。 它將遵循命名約定[YYYY-MM-DDrx] = [2020-01-0101r0]。
構建ESPv2 Docker映像 (Build ESPv2 Docker image)
We have our OpenAPI definition deployed. We have our API services deployed in Cloud Run, Cloud Functions and App Engine. Now we need to build an ESPv2 Docker image that holds the OpenAPI definition. The OpenAPI definition is what allows the ESPv2 proxy to understand what to do with requests; how to authenticate them and where to send them.
我們已經部署了OpenAPI定義。 我們將API服務部署在Cloud Run,Cloud Functions和App Engine中。 現在,我們需要構建一個包含OpenAPI定義的ESPv2 Docker映像。 ESPv2代理可以使用OpenAPI定義來了解如何處理請求。 如何進行身份驗證以及將其發送到哪里。
Fortunately, Google has created a script to do this for us. We only need to input the CONFIG_ID of our OpenAPI definition, the hostname of our proxy and our project id.
幸運的是,Google已經創建了一個腳本來為我們執行此操作。 我們只需要輸入OpenAPI定義的CONFIG_ID,代理的主機名和項目ID。
Download the script, make it executable and run the follow command.
下載腳本 ,使其可執行并運行follow命令。
$ chmod +x gcloud_build_image$ ./gcloud_build_image -s CLOUD_RUN_HOSTNAME \
-c CONFIG_ID -p PROJECT_ID
CLOUD_RUN_HOSTNAME is name of gateway e.g. gateway-<hash>-uc.a.run.appAfter a couple of minutes, the ESPv2 Docker image will complete its build and will be available in Container Registry. The name of the image will follow this naming convention.
CLOUD_RUN_HOSTNAME是網關的名稱,例如gateway- <hash> -uc.a.run.app。幾分鐘后,ESPv2 Docker鏡像將完成其構建并將在Container Registry中可用。 圖像名稱將遵循此命名約定。
gcr.io/<PROJECT_ID>/endpoints-runtime-serverless:ESP_VERSION-CLOUD_RUN_HOSTNAME-CONFIG_ID
gcr.io/<PROJECT_ID>/endpoints-runtime-serverless:ESP_VERSION-CLOUD_RUN_HOSTNAME-CONFIG_ID
部署ESPv2 Docker映像 (Deploy ESPv2 Docker image)
Now your ESPv2 proxy has been built you need to deploy it to Cloud Run.
現在您的ESPv2代理已經構建完畢,您需要將其部署到Cloud Run。
$ gcloud run deploy CLOUD_RUN_SERVICE_NAME \--image="gcr.io/$PROJECT_ID/endpoints-runtime-serverless:ESP_VERSION-CLOUD_RUN_HOSTNAME-CONFIG_ID" \
--allow-unauthenticated \
--region us-central1 \
--platform managed \
--project=$PROJECT_ID
激活API (Activate API)
By deploying the config on Cloud Endpoint, a new API service is created. Now, you have to activate it on your project. You can do this by command line:
通過在Cloud Endpoint上部署配置,可以創建新的API服務。 現在,您必須在項目上激活它。 您可以通過命令行執行此操作:
$ gcloud services enable gateway-<hash>-uc.a.run.appThe API service name is the name of your Cloud Run Endpoint gateway ENDPOINTS_SERVICE_NAME
API服務名稱是您的Cloud Run Endpoint網關ENDPOINTS_SERVICE_NAME
This API can be enabled and disabled the same way Google’s API’s are. You can call the private API from other GCP projects, providing your projects are part of an organisation.
可以使用與Google API相同的方式來啟用和禁用此API。 您可以從其他GCP項目中調用私有API,前提是您的項目是組織的一部分。
Go to APIs & Services > Dashboard > Enable APIs and Services > enable your private API.
轉到API和服務>儀表板>啟用API和服務>啟用您的私有API。
創建API密鑰 (Creating API Key)
For reaching the service, you have to use an API Key. For this you have to create one in Google Cloud console.
為了獲得服務, 您必須使用API??密鑰。 為此,您必須在Google Cloud控制臺中創建一個 。
Go to API & Services and select Credentials. Click on Create credentials and select API Key.
轉到API & Services然后選擇Credentials 。 點擊Create credentials ,然后選擇API Key 。
Because of the low level of security of an API Key, the best practice is to restrict the key.
由于API密鑰的安全性較低, 因此最佳做法是限制密鑰 。
Edit the key (click on the pencil), under API restrictions, click on Restrict key and, in the drop down list, only check your API Name.
編輯密鑰(單擊鉛筆),在“ API restrictions ,單擊“ Restrict key ,然后在下拉列表中僅檢查您的API名稱。
云端點授權 (Cloud Endpoint Authorization)
We have deployed three services and an Endpoint gateway. Now we need to give authorization to Endpoint so that that it will be able to access resources in services. Gateway endpoint service is deployed using <PROJECT_NUMBER>-compute@developer.gserviceaccount.com service account.
我們已經部署了三個服務和一個端點網關。 現在,我們需要授權給Endpoint,以便它能夠訪問服務中的資源。 網關端點服務是使用<PROJECT_NUMBER> -compute@developer.gserviceaccount.com服務帳戶部署的。
Cloud Run
云跑
As describe previously, a private Cloud Run service can be reached by authenticated user with roles/run.invoker. So, let’s grant this role to the Cloud Run Endpoint gateway service-account.
如前所述,經過身份驗證的用戶可以使用roles/run.invoker來訪問私有Cloud Run服務。 因此,讓我們將此角色授予Cloud Run Endpoint網關服務帳戶。
$ gcloud run services add-iam-policy-binding employee \--member "serviceAccount:$PROJECT_NUMBER-compute@developer.gserviceaccount.com" \
--role "roles/run.invoker" \
--platform managed \
--region us-central1 \
--project $PROJECT_ID
Cloud Functions
云功能
Like for Cloud Run, and as described previously, a private Cloud Functions service can be reached by authenticated user with roles/cloudfunctions.invoker.
與Cloud Run一樣,如前所述,經過身份驗證的用戶可以使用roles/cloudfunctions.invoker來訪問私有Cloud Functions服務。
$ gcloud functions add-iam-policy-binding employee \--region us-central1 \
--member "serviceAccount:$PROJECT_NUMBER-compute@developer.gserviceaccount.com" \
--role "roles/cloudfunctions.invoker" \
--project $PROJECT_ID
App EngineApp Engine is secured by IAP and we have already given access IAP-secured Web App User to Endpoint gateway service-account.
App Engine App Engine受IAP保護,我們已經授予了受IAP-secured Web App User訪問Endpoint Gateway服務帳戶的權限。
All the steps have been completed now let’s access the endpoints using proxy.
現在,所有步驟都已完成,現在讓我們使用代理訪問端點。
驗證云端點路由 (Validate Cloud Endpoints routes)
All the steps have been completed now let’s access the endpoints using proxy.
現在,所有步驟都已完成,現在讓我們使用代理訪問端點。
POST the employeecurl POST https://gateway-<hash>-uc.a.run.app/employee?key=API_KEY --header 'Content-Type: application/json' --data-raw '{"id": 11223344, "firstname": "Vikram", "lastname": "Shinde"}'
curl POST https://gateway-<hash>-uc.a.run.app/employee?key=API_KEY --header 'Content-Type: application/json' --data-raw '{"id": 11223344, "firstname": "Vikram", "lastname": "Shinde"}'員工curl POST https://gateway-<hash>-uc.a.run.app/employee?key=API_KEY --header 'Content-Type: application/json' --data-raw '{"id": 11223344, "firstname": "Vikram", "lastname": "Shinde"}'
GET the employeecurl https://gateway-<hash>-uc.a.run.app/employee/11223344?key=API_KEY
獲取員工curl https://gateway-<hash>-uc.a.run.app/employee/11223344?key=API_KEY
DELETE the employeecurl DELETE https://gateway-<hash>-uc.a.run.app/employee/11223344?key=API_KEY
刪除員工curl DELETE https://gateway-<hash>-uc.a.run.app/employee/11223344?key=API_KEY
API密鑰的最佳做法 (Best practices with API Keys)
API keys are not secure way and it can be easily stolen as any man-in-the-middle attack or packet sniffer tool can read them as plain text.
API密鑰不是安全的方式,并且很容易被盜,因為任何中間人攻擊或數據包嗅探工具都可以將它們讀取為純文本格式。
Hence there are some best practices for using API Keys
因此,有一些使用API??密鑰的最佳做法
Apply API key restrictions. API keys are unrestricted by default.
應用API密鑰限制。 默認情況下,API密鑰不受限制。
使用Bearer Auth令牌進行身份驗證 (Authenticate with Bearer Auth Token)
After successfully creating an OpenAPI definition, and building an ESPv2 proxy for API key authentication, moving to bearer authentication will be easy.
成功創建OpenAPI定義并構建用于API密鑰身份驗證的ESPv2代理后,轉移到承載身份驗證將很容易。
資源資源 (Resources)
Server to server bearer auth
服務器到服務器承載身份驗證
承載身份驗證在Cloud Endpoints中的工作方式 (How bearer auth works in Cloud Endpoints)
There are different types of bearer authentication you can use with Cloud Endpoints. You can use server-to-server or OAuth2.0 (Google ID token) auth. We’ll be using server-to-server auth. However, OAuth works very similarly to server-to-server, so do some reading if you require users to interact with your API.
您可以對Cloud Endpoints使用不同類型的承載身份驗證。 您可以使用服務器到服務器或OAuth2.0(Google ID令牌)auth 。 我們將使用服務器到服務器身份驗證。 但是,OAuth的工作原理與服務器到服務器非常相似,因此如果您需要用戶與API進行交互,請閱讀一些內容。
The following notes are the steps the proxy will follow to authenticate the request. Use these notes when referencing the Cloud Endpoints architecture.
以下注釋是代理將對請求進行身份驗證的步驟。 引用Cloud Endpoints架構時,請使用這些說明。
Service Control authenticates the bearer token
服務控制對承載令牌進行身份驗證
the bearer token is decoded and checks the following:
承載令牌被解碼并檢查以下內容:
- the token is not expired
-令牌未過期
- issuer is correct
-發行人是正確的
- verifies the signature : checks the private certificate in the token against the public certificate
-驗證簽名:對照公共證書檢查令牌中的私有證書
為承載身份驗證配置OpenAPI定義 (Configure the OpenAPI definition for Bearer Auth)
Let’s update our openapi-definition.yaml to include bearer auth for POST and DELETE methods
讓我們更新我們的openapi-definition.yaml以包括POST和DELETE方法的承載認證
bearer:
authorizationUrl: ""
flow: "implicit"
type: "oauth2"
x-google-issuer: "email_of_sa"
x-google-jwks_uri: "https://www.googleapis.com/robot/v1/metadata/x509/email_of_sa"
x-google-jwt-locations:
- header: "Authorization"
value_prefix: "Bearer "
Update the email_of_sa with service account email.Change security flag from api-key to bearer
使用服務帳戶email更新email_of_sa。將安全性標志從api-key更改為bearer
security:-
Redeploy
重新部署
Since definition has been change, we need to deploy OpenAPI definition, rebuild and redeploy gateway service.
由于定義已更改,因此我們需要部署OpenAPI定義,重建并重新部署網關服務。
$ gcloud endpoints services deploy openapi-definition.yamlIt will generate new CONFIG_ID. e.g. [2020–01–01r1]
它將生成新的CONFIG_ID。 例如[2020-01-01r 1 ]
$ ./gcloud_build_image -s CLOUD_RUN_HOSTNAME \-c CONFIG_ID -p ESP_PROJECT_ID
This will generate new version of image
這將生成新版本的圖像
$ gcloud run deploy CLOUD_RUN_SERVICE_NAME \--image="gcr.io/ESP_PROJECT_ID/endpoints-runtime-serverless:ESP_VERSION-CLOUD_RUN_HOSTNAME-CONFIG_ID" \
--allow-unauthenticated \
--platform managed \
--project=ESP_PROJECT_ID
You can use following Python code to create a bearer token.
您可以使用以下Python代碼創建承載令牌。
import time import google.auth.crypt import google.auth.jwtsa_keyfile = 'path_of_service_account' iss = 'email_address_of_service_account' aud = 'hostname_of_your_gateway' iat = int(time.time()) exp = iat + 3600def generate_jwt():"""Generates a signed JSON Web Token using a Google API Service Account."""payload = {"iat": iat, "exp": exp, "iss": iss, "aud": aud, "sub": iss, "email": iss}signer = google.auth.crypt.RSASigner.from_service_account_file(sa_keyfile)jwt = google.auth.jwt.encode(signer, payload)return jwtif __name__ == '__main__':signed_jwt = generate_jwt()print(signed_jwt.decode()+'\n')Once bearer token is generated, make a request to the proxy with the token.
生成承載令牌后,請使用令牌向代理發出請求。
curl --request POST \--header "Authorization: Bearer ${token}" \
"https://gateway-{hash}-uc.a.run.app/employee" \
--header 'Content-Type: application/json' \
--data-raw '{
"id": 411,
"last": "vikram",
"name": "Shinde"
}'
API配額 (Quotas for API)
Cloud Endpoints provides quotas which let you control the rate at which applications can call your API. Setting a quota lets you specify usage limits to protect your API from an excessive number of requests from calling applications.
Cloud Endpoints提供了配額,可讓您控制應用程序調用API的速率。 通過設置配額,您可以指定使用限制,以保護API免受來自調用應用程序的過多請求。
Add following 3 sections in openapi-definition.yaml file.
在openapi-definition.yaml文件中添加以下3個部分。
- metrics: A named metric that counts requests to your API. 指標:一種命名指標,用于統計對您的API的請求。
- limit: Represents a enforced limit on the named metrc. limit:表示對命名的metrc的強制限制。
- metricCosts: The metricCosts maps methods to metrics. metricCosts:metricCosts將方法映射到指標。
metrics:
- name: "YOUR_METRIC_NAME"
displayName: "YOUR_METRIC-DISPLAY_NAME"
valueType: INT64
metricKind: DELTA
metricKind and valueType must be DELTA and INT64
metricKind和valueType必須為DELTA和INT64
quota:limits:
- name: "YOUR_LIMIT_NAME"
metric: "YOUR_METRIC_NAME"
unit: "1/min/{project}"
values:
STANDARD: VALUE_FOR_THE_LIMIT
In the paths sections add x-google-quota extension under the method.
在路徑部分中,在方法下添加x-google-quota擴展名。
x-google-quota:metricCosts:
YOUR_METRIC_NAME: YOUR_METRIC_COST
In our example, I have added quota in GET API to limit 5 requests per minute.
在我們的示例中,我在GET API中添加了配額,以限制每分鐘5個請求。
paths:/employee/{employee_id}:
get:
summary: Get an Employee
operationId: getEmployee
x-google-backend:
address: https://us-central1-<PROJECT_ID>.cloudfunctions.net/employeeprotocol: h2
parameters:
- name: employee_id
in: path
responses:
....
security:
- api_key: []
x-google-quota:
metricCosts:
"api_requests": 1
....x-google-management:
metrics:
- name: api_requests
valueType: INT64
metricKind: DELTA
quota:
limits:
- name: limit-on-api-requests
metric: "YOUR_METRIC_NAME"
unit: "1/min/{project}"
values:
STANDARD: 5
After redeploying the gateway service, I called the GET endpoints multiple times within a minutes and I received following error.
重新部署網關服務后,我在一分鐘內多次調用GET端點,并且收到以下錯誤。
$ curl https://gateway-6bpnwgtf6q-uc.a.run.app/employee/111?key=API_KEY{"code":429,"message":"RESOURCE_EXHAUSTED:Quota exceeded for quota metric 'api_requests' and limit 'limit-on-api-requests' of service 'gateway-6bpnwgtf6q-uc.a.run.app' for consumer 'project_number:499537266481'."}跟蹤API活動 (Tracking the API activity)
View the activity graphs for your API on Endpoints → Service page.
在“端點”→“服務”頁面上查看API的活動圖。
You can also track the activities from APIs & Services → API → Metrics.
您還可以從API和服務→API→指標跟蹤活動。
結論 (Conclusion)
In this tutorial, we have secured APIs on Cloud Run, Cloud Functions, App Engine with Cloud Endpoints ESPV2 using API Key and Bearer token. Also we have seen how to add quotas and rate limits and track the API activities.
在本教程中,我們使用API??密鑰和Bearer令牌保護了Cloud Run,Cloud Functions,帶有Cloud Endpoints ESPV2的App Engine上的API安全。 此外,我們還看到了如何添加配額和速率限制以及如何跟蹤API活動。
Cloud Endpoints is almost free. First 2 Millions API calls per month is free and $3.00 per million thereafter.
Cloud Endpoints幾乎是免費的。 每月前200萬次API調用是免費的,其后每百萬次調用$ 3.00。
If you look for advance features on API management, Apigee is the option.
如果您需要API管理方面的高級功能, 則可以選擇Apigee 。
Please feedback how find this tutorial and connect me on LinkedIn.
請反饋如何找到本教程并在LinkedIn上與我建立聯系。
翻譯自: https://medium.com/swlh/secure-apis-in-cloud-run-cloud-functions-and-app-engine-using-cloud-endpoints-espv2-beta-b51b1c213aea
總結
以上是生活随笔為你收集整理的云中的安全api使用云端点espv2 beta运行云功能和应用程序引擎的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【yoyo】jvm中堆栈以及内存区域分配
- 下一篇: 图像类找工作面试题(二)——常见问题大总