Google Oauth Authentication Example Code

269 views
Skip to first unread message

Amar Shiva Prasad

unread,
Feb 25, 2014, 11:07:40 AM2/25/14
to google-analytics...@googlegroups.com
I am very new to use google API'S. I am trying to authenticate my gmail account using a java program. For this I am using google Oauth authentication but when I execute this I am getting the below exception.

    com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
    {
      "error" : "invalid_grant"
    }
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest.execute(GoogleAuthorizationCodeTokenRequest.java:158)
at com.google.drive.auth.impl.OauthAuthentication.authenticate(OauthAuthentication.java:44)
at com.google.drive.auth.impl.OauthAuthentication.main(OauthAuthentication.java:58)

I am pasting the code.

    public class OauthAuthentication implements Authentication<Credential> {

private static String CLIENT_ID = "<CLIENT_ID>";
private static String CLIENT_SECRET = "<CLIENT_SECRET>";
private static String REDIRECT_URI = "https://www.google.com/";

@Override
public Credential authenticate() {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
GoogleAuthorizationCodeFlow googleAuthorizationCodeFlow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, CLIENT_ID, CLIENT_SECRET,
Arrays.asList(DriveScopes.DRIVE)).setAccessType("online")
.setApprovalPrompt("auto").build();
String redirectUrl = googleAuthorizationCodeFlow.newAuthorizationUrl()
.setRedirectUri(REDIRECT_URI).build();

System.out
.println("Please open the following URL in your browser then type the authorization code:");
System.out.println("  " + redirectUrl);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
String code = br.readLine();
GoogleTokenResponse googleTokenResponse = googleAuthorizationCodeFlow
.newTokenRequest(code).setRedirectUri(REDIRECT_URI)
.execute();
GoogleCredential googleCredential = new GoogleCredential()
.setFromTokenResponse(googleTokenResponse);
System.out.println(googleCredential.getServiceAccountUser());
return googleCredential;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

public static void main(String[] args) {
OauthAuthentication oauthAuthentication = new OauthAuthentication();
oauthAuthentication.authenticate();
}
    }

This is the code for authenticating my gmail account. 

Can anyone help me on this what's wrong here ...??? Or else can anyone point me to the right location for Oauth sample code.

Thanq in advance.

Reply all
Reply to author
Forward
0 new messages