【发布时间】:2022-04-05 20:14:50
【问题描述】:
我们正在尝试在我们的产品中使用 Google OAuth。流程是让客户端从用户那里获取身份验证并将令牌发送到服务器。在服务器端,我需要验证令牌是否有效。目前,我使用 Google 提供的 OAuth2Sample 作为客户端。当我在服务器端验证发送的令牌时,出现以下异常:
com.google.api.client.auth.oauth2.TokenResponseException: 400 错误请求
{
“错误”:“invalid_grant”,
"error_description" : "验证码格式错误。"
}在 com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
在 com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287) 在 com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest.execute(GoogleAuthorizationCodeTokenRequest.java:158)
这是服务器端的代码:
GoogleTokenResponse tokenResponse =
new GoogleAuthorizationCodeTokenRequest(
new NetHttpTransport(),
JacksonFactory.getDefaultInstance(),
"https://www.googleapis.com/oauth2/v4/token",
CLIENT_ID,
CLIENT_SECRET,
authToken, //Sent from the client
"") // specify an empty string if you do not have redirect URL
.execute();
这是我在客户端获取访问令牌的方式:
private static final List<String> SCOPES = Arrays.asList(
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/userinfo.email");
//...
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, JSON_FACTORY,
clientSecrets, //Client ID and Client Secret
SCOPES).setDataStoreFactory(
dataStoreFactory).build();
LocalServerReceiver lsr = new LocalServerReceiver();
Credential cr = new AuthorizationCodeInstalledApp(flow, lsr).authorize("user");
return cr.getAccessToken(); //send this to server for verification
令牌在前往服务器的途中没有损坏,它是:
ya29.Glx_BUjV_zIiDzq0oYMqoXkxz8VGzt8GCQuBiaaJ3FxN0qaLxbBXvnWXjNKZbpeu4jraoEqw6Mj9D7LpTx_8Ts_8TH0VGT5cbrooGcAOF0wKMc1DDEjm6p5m-MvtFA
如果我尝试从客户端访问个人资料和电子邮件,它工作正常。相同的令牌在服务器端不起作用得到格式错误的令牌异常。
【问题讨论】:
-
问题解决了吗?
标签: java google-oauth