Invalid_grant,Google OAuth2中的代码无效

时间:2014-08-30 06:18:14

标签: google-oauth google-oauth-java-client

我正在尝试使用Google OAuth2 API获取基本用户个人资料信息,但在尝试获取访问/刷新令牌时失败,说Invalid_grant和错误说明无效代码。以下是我获取令牌的代码

public static String getUserInfoJson(final String authCode) throws IOException{

    GoogleTokenResponse response = flow.newTokenRequest(authCode)
                .setRedirectUri(CALLBACK_URI)
                .execute();
    Credential credential = flow.createAndStoreCredential(response,
                null);
    final HttpRequestFactory requestFactory = HTTP_TRANSPORT
            .createRequestFactory(credential);
    // Make an authenticated request
    final GenericUrl url = new GenericUrl(USER_INFO_URL);
    final HttpRequest request = requestFactory.buildGetRequest(url);
    request.getHeaders().setContentType("application/json");
    final String jsonIdentity = request.execute().parseAsString();

    return jsonIdentity;

}

以下是我创建authCode的代码

    private static final String CLIENT_ID = "CLIENT_ID_BUT_NOT_EMAIL_ID"; //Not emailid
    private static final String CLIENT_SECRET = "SecretKey";
    private static final String CALLBACK_URI = "http://localhost:8080/Spring4MVCHelloWorld/OAuthRedirect";
    private static final String ACCESS_TYPE = "offline";

    private static final Iterable<String> SCOPE = Arrays
        .asList("https://www.googleapis.com/auth/userinfo.profile;https://www.googleapis.com/auth/userinfo.email"
                .split(";"));
    private static final String USER_INFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo";
    private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    private String stateToken;

    private static GoogleAuthorizationCodeFlow flow;

    public GoogleAuthHelper() {
        flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,
            JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, SCOPE)
            .setAccessType(ACCESS_TYPE)
            .build();

        generateStateToken();
    }

    public String buildLoginUrl() {

        final GoogleAuthorizationCodeRequestUrl url = flow
            .newAuthorizationUrl();

        return url.setRedirectUri(CALLBACK_URI).setState(stateToken).build();
    }

    private void generateStateToken() {

        SecureRandom sr1 = new SecureRandom();

        stateToken = "google;" + sr1.nextInt();

    }

    public String getStateToken() {
        return stateToken;
    }

用户被成功重定向到重定向URL,但随后对getUserInfoJson的调用失败并返回400响应。 我已经经历了许多与此类似的SO问题但无济于事。

0 个答案:

没有答案