这是一个相当长的过程:
关注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 请求新的。但是,这不在这个问题的范围内。