一只甜甜圈
所以这就是我的做法:在客户端(Angular 应用程序),我使用 ngx-auth-firebaseui 来显示登录表单。在表单上,我设置了处理身份验证成功的回调:login.component.html<ngx-auth-firebaseui (onSuccess)="successfulLogin($event)" (onError)="printError($event)"></ngx-auth-firebaseui>回调的代码在这里。从 Firebase 用户对象中,我调用 getIdTokenResult() 方法来获取 Firebase JWT。然后我通过 authenticationService 调用我的 php 后端登录组件.tssuccessfulLogin(user:User) { console.log(user); user.getIdTokenResult().then((idTokenResult:IdTokenResult)=> { console.log(idTokenResult.token); let token : string = idTokenResult.token; let rcqJWTToken = this.authenticationService.authenticate( { token } as FirebaseJWT); rcqJWTToken.subscribe((rcqToken:string)=> console.log("RCQ JWT Token : '"+rcqToken+"'")); this.router.navigate['/welcome']; }); }在这里,我将 Firebase JWT 传输到我的 php 后端 authentication.service.ts authenticate(firebaseJWTToken:FirebaseJWT):Observable<String>{ return this.http.post<String>(this.authenticationURL, firebaseJWTToken, httpOptions) .pipe( tap(_ => console.log('fetched RCQ JWT')), catchError(this.handleError<String>('authenticate', "")) ); }在服务器端:我将 GOOGLE_APPLICATION_CREDENTIALS 设置为环境变量,就像在 Google App Engine 上部署时一样putenv("GOOGLE_APPLICATION_CREDENTIALS=/Users/myuser/.cred/GCP-project-ID.json");我使用 Slimframework,所以我在我的 dependencies.php 文件中实例化了 Firebase 对象。使用 env var,Firebase 不需要其他任何东西。在这里检查:https ://firebase-php.readthedocs.io/en/4.32.0/setup.htmluse Kreait\Firebase;use Kreait\Firebase\Factory;/** * Used to authenticate a firebase user, from it's Firebase JWT * @property Firebase $firebase * @param \Slim\Container $c * @return Firebase */$container['firebase'] = function (\Slim\Container $c){ $firebase = (new Factory)->create(); return $firebase;};这是完成身份验证的路线:$app->post(getPrefix().'/firebase-authenticate', function($request, $response, $args) use ($app){ $token = $this->clientInputValidator->validateString("token" , $request->getParsedBodyParam("token" ), 1500 , true ); $username = ""; Logger::dataForLogging(new LoggingEntity(null, ["username"=>$username])); try { $verifiedIdToken = $this->firebase->getAuth()->verifyIdToken($token); } catch (InvalidToken $e) { $response401 = $response->withStatus(401); $response401->getBody()->write(json_encode(["error" =>"Authentication error"])); $this->logger->error("Firebase authentication error", array('username' => $username, 'token' => $token)); return $response401; } $uid = $verifiedIdToken->getClaim('sub'); $user = $this->firebase->getAuth()->getUser($uid); $this->logger->debug("Firebase JWT checked successfully", array('uid' => $uid,'user' => $user));});主要的在这里: $verifiedIdToken = $this->firebase->getAuth()->verifyIdToken($token);并在此处检索用户详细信息:$user = $this->firebase->getAuth()->getUser($uid);我可以在 Firebase JWT 中获取 uid、电子邮件和所有信息。令牌本身的 TTL 为 1 小时,因此我可能必须刷新令牌并针对我的后端重新验证它。