使用令牌从本地运行的Google Cloud应用程序检索Firebase用户

时间:2019-01-11 04:24:27

标签: java firebase google-cloud-platform firebase-authentication

我正在研究充当端点API的Java API,并正在生产  它在Google Cloud Platform上运行。通过将Firebase令牌作为URL的一部分传递来调用API方法,该令牌用于创建User,该方法可在API方法中使用:

@ApiMethod(path = "myPath/{tokenId}/doSomething", httpMethod = "get")
    public ResponseMessage ReturnSomething(@Named("tokenId") String tokenId, User user) throws UnauthorizedException, BadRequestException, InternalServerErrorException, FirebaseAuthException  
    {
        if (user == null)
        ...

在生产中,当从Firebase上的Angular应用程序调用URL并传递URL中的令牌时,将正确创建user。我不完全了解如何从令牌创建User,我只知道它以某种方式“自动”发生在Firebase与Google Cloud集成中。

我想通过从Eclipse内部使用 Debug As> App Engine 在本地调试API。但是,当我这样做并从使用Firebase serve运行的本地Angular应用程序调用API时,令牌已正确传递到本地运行的API,但是user始终为null

@ApiMethod(path = "myPath/{tokenId}/doSomething", httpMethod = "get")
    public ResponseMessage ReturnSomething(@Named("tokenId") String tokenId, User user) throws UnauthorizedException, BadRequestException, InternalServerErrorException, FirebaseAuthException  
    {
        if (user == null)
        // this is always null

我怀疑这是我在本地运行的Java API正确向Firebase进行身份验证时出现的问题。我看过this guide,它建议将Windows上的GOOGLE_APPLICATION_CREDENTIALS属性设置为App Engine默认服务帐户的JSON密钥的路径,这是确保本地授予对Google Cloud(可能还有Firebase)资源的访问权限。

我已经明确添加了此内容(无论如何,我已经使用命令行运行了gcloud auth application-default login),但是它仍然无法正常工作。我只是得到null的{​​{1}}而没有任何迹象表明发生了什么。我不想以编程方式进行身份验证,因为这意味着更改API代码以在调试期间进行不同的身份验证。作为App Engine在本地进行调试时,如何获取user

更新

我已经意识到,尽管URL中存在User,但是在调用API时出现以下错误:

tokenId

下面的代码中的WARNING: Authentication failed: com.google.api.auth.UnauthenticatedException: No auth token is contained in the HTTP request 值是有效值,因此我不确定为什么收到此消息:

tokenId

1 个答案:

答案 0 :(得分:0)

我发现这实际上是Auth0库的问题,该库在Angular中用于支持对Java API进行身份验证的HTTP请求。每当从Angular应用程序调用Angular Bearer时,使用Auth0库将auth令牌注入到请求标头的http.get中。 User的创建取决于HTTP标头中的 中存在的此属性,其值设置为auth令牌的值。

我通过更改该库的配置来解决此问题。我需要将运行API的端口(8080)暂时列入localhost的白名单,以允许Auth0在有localhost:8080

的请求时将令牌注入HTTP标头中
const jwtConf: JwtModuleOptions = {
  config: {
    tokenGetter: getToken,
    whitelistedDomains: ['localhost:8080']
  }
};