我正在为我的应用创建私有API,并尝试通过Google Auth保护它。如何在每个请求中获取一些新令牌,以便随后可以在我自己的服务器上使用一些密钥对其进行验证?
在Firebase仪表板中,我看到了Web客户端机密,但没有有关如何使用它的文档,也没有此机密是什么。
或者也许您知道一些有关如何仅针对一种应用程序使用创建私有API的良好做法。谢谢!
答案 0 :(得分:3)
这是一个相当漫长的过程:
按照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请求一个新的密码。但是,这不在此问题的范围内。