【问题标题】:private API using Firebase Authentication使用 Firebase 身份验证的私有 API
【发布时间】:2018-07-02 20:27:30
【问题描述】:

我正在为我的应用创建私有 API,并尝试使用 Google Auth 对其进行保护。如何在每个请求中获取一些新令牌,以便我可以在自己的服务器上使用一些密钥对其进行验证?

在 Firebase 仪表板中,我看到了 Web 客户端密码,但没有任何文档说明如何使用它,也没有任何文档说明这个密码是什么。

或者,也许您知道一些关于如何为一种应用程序创建私有 API 的良好做法。谢谢!

【问题讨论】:

    标签: android firebase firebase-authentication


    【解决方案1】:

    这是一个相当长的过程:

    关注https://developers.google.com/identity/sign-in/android/ 使用 Google Auth 进行基本登录。

    为了在后台使用授权,有一些修改 -

    第 1 步 - 由于您已经找到了客户端机密文件,因此请使用客户端机密 ID 来获取 serverAuthCode。喜欢-

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestServerAuthCode(clientSecrets.getDetails().getClientId(), true)
                    .requestEmail()
                    .build();
    

    第 2 步 - 在链接中显示的 handleSignInResult 方法中,您可以获得您将发送到您的服务器的 authCode。

    account.getServerAuthCode();
    

    第 3 步 - 在您的服务器中,您可以获得访问令牌。这个 accessToken 用于使用几乎所有的 Google API。基本上,获取 accessToken 意味着您的后端已通过 Google 身份验证。

    将客户端机密文件添加到您的后端。

    GoogleClientSecrets clientSecrets =
                    GoogleClientSecrets.load(
                            JacksonFactory.getDefaultInstance(), new InputStreamReader(getAssets().open(Constants.CLIENT_SECRET_FILE_PATH)));
    
    
     if(!authCode.isEmpty()) {
                GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(
                        new NetHttpTransport(),
                        JacksonFactory.getDefaultInstance(),
                        "https://www.googleapis.com/oauth2/v4/token",
                        clientSecrets.getDetails().getClientId(),
                        clientSecrets.getDetails().getClientSecret(),
                        authCode,
                        "")
                        .execute();
    
                accessToken = tokenResponse.getAccessToken();
        }
    

    还有几个步骤,因为 authCode 只能使用一次,并且 accessToken 会在一段时间后过期,您必须使用 refreshToken 请求新的。但是,这不在这个问题的范围内。

    【讨论】:

      猜你喜欢
      • 2019-02-14
      • 2023-03-26
      • 2018-07-27
      • 1970-01-01
      • 2019-08-17
      • 2022-08-19
      • 1970-01-01
      • 2019-03-23
      • 2012-10-27
      相关资源
      最近更新 更多