当从webapp代理firebase功能时,如何验证当前用户?

时间:2018-02-04 13:22:28

标签: javascript firebase firebase-authentication google-cloud-functions

我有一个firebase应用程序,它有一个代理函数的url,使用"重写" firebase.json文件中的功能。对https://myapp.com/hello的请求将被发送到' helloWorld'功能

"rewrites": [
      {
    "source": "/hello",
    "function": "helloWorld"
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]

是否可以确定请求的经过身份验证的用户?由于请求基于与应用程序相同的URI方案,我认为这是可能的,但我看到的只是connect.sid cookie,而且不是授权令牌。

1 个答案:

答案 0 :(得分:1)

我已经弄明白了,您需要使用当前登录用户的令牌手动设置__session cookie。

以下是我在角度firebase应用程序中的AuthService中的操作方法。

 this.firebaseAuth.authState.subscribe( currentUser => {
      this.authenticatedUser = currentUser;
      if (currentUser === null) {
        this.cookieService.delete("__session");
      } else {
        currentUser.getIdToken().then(token =>
          cookieService.set('__session', token)
        );
      }
    });

然后在你的功能中你可以这样做:

admin.auth().verifyIdToken(idToken).then(decodedIdToken => {
  console.log('ID Token correctly decoded', decodedIdToken);
  req.user = decodedIdToken;
}

其中idToken是__session cookie中的值。