如何从 Java 中的 serverAuthCode 获取 google 访问令牌?
How to get google access token from serverAuthCode in Java?
我正在使用 https://github.com/react-native-google-signin/google-signin ,在我的 UI 中我有 serveAuthCode,
但我无法弄清楚如何从 java 后端的此 serverAuthCode 获取访问令牌。
任何帮助将不胜感激。
类似问题:link
在我的例子中,我从 https://github.com/react-native-google-signin/google-signin、
获取 serverAuthCode
在后端然后你可以做下面的代码
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static final JsonFactory JSON_FACTORY = new JacksonFactory();
GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY,
Your_OAUTH_CLIENTID,
Your_OAUTH_CLIENTSECRET,
Serverauthcode_from_react_native, "")
.execute();
//下面的代码让你获得更长有效期的令牌
GoogleCredential refreshTokenCredential = new GoogleCredential.Builder()
.setJsonFactory(Auth.JSON_FACTORY)
.setTransport(Auth.HTTP_TRANSPORT)
.setClientSecrets(Your_OAUTH_CLIENTID, Your_OAUTH_CLIENTSECRET)
.build()
.setRefreshToken(response.getRefreshToken());
refreshTokenCredential.refreshToken();
String newAccessToken = refreshTokenCredential.getAccessToken();
注意:serverAuthCode 只能使用一次,从你得到的响应中你应该存储 refreshToken,并且从下次使用 refreshToken 来获取你的 AccessToken
我正在使用 https://github.com/react-native-google-signin/google-signin ,在我的 UI 中我有 serveAuthCode, 但我无法弄清楚如何从 java 后端的此 serverAuthCode 获取访问令牌。 任何帮助将不胜感激。
类似问题:link
在我的例子中,我从 https://github.com/react-native-google-signin/google-signin、
获取 serverAuthCode在后端然后你可以做下面的代码
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
public static final JsonFactory JSON_FACTORY = new JacksonFactory();
GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY,
Your_OAUTH_CLIENTID,
Your_OAUTH_CLIENTSECRET,
Serverauthcode_from_react_native, "")
.execute();
//下面的代码让你获得更长有效期的令牌
GoogleCredential refreshTokenCredential = new GoogleCredential.Builder()
.setJsonFactory(Auth.JSON_FACTORY)
.setTransport(Auth.HTTP_TRANSPORT)
.setClientSecrets(Your_OAUTH_CLIENTID, Your_OAUTH_CLIENTSECRET)
.build()
.setRefreshToken(response.getRefreshToken());
refreshTokenCredential.refreshToken();
String newAccessToken = refreshTokenCredential.getAccessToken();
注意:serverAuthCode 只能使用一次,从你得到的响应中你应该存储 refreshToken,并且从下次使用 refreshToken 来获取你的 AccessToken