I am trying to obtain basic user profile information using Google OAuth2 API but it fails while trying to fetch the access/refresh tokens saying Invalid_grant and error description Invalid Code. Following is my code to fetch the token
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;
}
Following is my code to create the 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;
}
User is redirected successfully to the redirect URL but the subsequent call to getUserInfoJson fails with a a 400 response. I have gone through many SO questions similar to this to no avail.