使用gcp oauth验证请求并在flask中发送cors头的一个小实用程序
gcloud-flask-oauth-cors的Python项目详细描述
一个小类,用于用python编写并托管在gcp上的http触发的云函数的身份验证和cors
请注意:这不是官方支持的谷歌产品。
如果您使用oauth对Cloud Function written in Python进行身份验证并托管在gcp上,并且您的客户机在浏览器中运行,则这是为您准备的。如果没有,你可能不会觉得这有用。
这门课做三件事:
- 正确且可配置地响应浏览器用作CORS的飞行前检查的HTTP选项方法
- 检索在
Authorization
http报头中提供的oauth2令牌,对其进行验证,然后获取由该令牌编码的信息 - 返回有效的令牌,或在找不到有效令牌时返回给用户的响应
安装
您可以使用pip:
python3 -m pip install --user gcloud-flask-oauth-cors
它托管在pypi上:https://pypi.org/project/gcloud-flask-oauth-cors/
使用
如果没有,请使用云函数create an OAuth client ID和pass it as an environment variable然后,您可以使用以下命令:
import gcloud_flask_oauth_cors as oauth
def my_function_name(request):
auth = oauth.Auth(os.getenv("OAUTH_CLIENT_ID"))
id_info = auth.get_id_info(request)
if id_info is None:
# If we were called with the HTTP OPTIONS method, this will return the relevant CORS headers.
# If another HTTP method was used and we can't authenticate, this will return a 401 (Unauthorized)
return auth.get_response()
# Do something with the id_info, for example:
print(id_info["sub"])
在客户端,可以使用Google Sign-in。确保在任何此类请求中都传递id_token
:
let xhr = new XMLHttpRequest();
xhr.setRequestHeader("Authorization", "Bearer " + id_token);