Workspace用户如何调用云函数?

How To Invoke Cloud Functions With Workspace Users?

我正在尝试通过我在 App Engine 上托管的 angular 应用程序调用 GCP 功能。鉴于我的用户不是通过 GCP 而是通过 Google Workspace 注册的,我似乎找不到任何直接的答案。所以简而言之,我正在构建的应用程序仅供内部用户使用。截至目前,我可以使用 Google 身份验证正常登录,问题是在我登录后,云功能拒绝了我的请求。我已经包括了我采取的所有步骤以及我从云功能收到的错误。

这就是我到目前为止所做的。

我的代码如下:

DashboardComponent.ts

import {SocialAuthService} from 'angularx-social-login';

...

this.authService.authState.subscribe((user) => {
    this.myService.callFunction(user.idToken).subscribe((userRes) => {
    ...
}

...

FirebaseFunctionService.ts

  callFunction(authToken): Observable<any> {
    const headers= new HttpHeaders()
      .set('content-type', 'application/json')
      .set('Access-Control-Allow-Origin', '*')
      .set('Authorization', `Bearer ${authToken}`);
    
    return this.http.get('https://my-cloud-function-url/my-function',  { headers: headers 
    });
  }

调用此函数时得到的响应是:

error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: 'error', …} headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)} message: "Http failure response for https://myFunction.cloudfunctions.net/myFunction: 0 Unknown Error" name: "HttpErrorResponse" ok: false status: 0 statusText: "Unknown Error" url: "https://myFunction.cloudfunctions.net/myFunction" [[Prototype]]: HttpResponseBase

有谁知道为什么会这样?任何帮助将不胜感激,因为我无能为力。提前致谢:)

错误消息中的状态代码 0 表示 CORS 失败。您可以查看此 GitHub issue comment,其中 Whosebug 线程指出了导致此错误的多种原因。

你还需要在初始化中写下这行代码:

const cors = require('cors')({origin: true}) 并查看 Google’s documentation 如何处理 CORS 请求。此外,您还必须提供适当的权限 - 重要的权限之一是将 Cloud Functions 调用者角色授予您的云功能。

Joe,(我们的问题的作者)同意这是一个 CORS 错误,但他通过给予 allUsers 权限(使函数 public)并在函数本身中验证用户来解决它CORS 消失了。

这背后的原因:

我认为 Joe 的身份验证机制存在一些问题,因此功能未通过身份验证。 HTTP functions require authentication by default. And as it did not have it, as per documentation 解决方法是通过设置 --allow-unauthenticated 标志使 Joe 的功能 public,或者使用控制台授予 Cloud Functions Invoker role to allUsers。然后在功能代码中处理 CORS 和身份验证(正如他所说的那样)。

因此,当 Joe 通过授予 allUsers 并在代码中处理 CORS 来创建函数 public 时,它开始工作并且 CORS 错误消失了。