我们正在尝试在我们的产品中使用 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();
Run Code Online (Sandbox Code Playgroud)
这是我在客户端获取访问令牌的方法:
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
Run Code Online (Sandbox Code Playgroud)
令牌在通往服务器的途中没有损坏,它是:
ya29.Glx_BUjV_zIiDzq0oYMqoXkxz8VGzt8GCQuBiaaJ3FxN0qaLxbBXvnWXjNKZbpeu4jraoEqw6Mj9D7LpTx_8Ts_8TH0VGT5cbrooGcAfmDcFAM
如果我尝试从客户端访问个人资料和电子邮件,它工作正常。相同的令牌在服务器端不起作用获取格式错误的令牌异常。
sli*_*wp2 16
我正在使用Node.jsgoogleapis 客户端库,这是我的案例:
url hash 片段中的授权码是通过encodeURIComponentapi编码的,所以如果你通过这个码来请求访问令牌。它会抛出一个错误:
{ "error": "invalid_grant", "error_description": "Malformed auth code." }
所以我decodeURIComponent用来解码授权码。
decodeURIComponent('4%2F_QCXwy-PG5Ub_JTiL7ULaCVb6K-Jsv45c7TPqPsG2-sCPYMTseEtqHWcU_ynqWQJB3Vuw5Ad1etoWqNPBaGvGHY')
Run Code Online (Sandbox Code Playgroud)
解码后授权码为:
"4/_QCXwy-PG5Ub_JTiL7ULaCVb6K-Jsv45c7TPqPsG2-sCPYMTseEtqHWcU_ynqWQJB3Vuw5Ad1etoWqNPBaGvGHY"
Run Code Online (Sandbox Code Playgroud)
在 Java 中,也许您可以使用URLDecoder.decode处理代码。
| 归档时间: |
|
| 查看次数: |
5606 次 |
| 最近记录: |