Andrea Zonzin Andrea Zonzin - 8 months ago 76
Java Question

Authenticate programmatically to Google with OAuth2

How can I authenticate programmatically to Google?
Now that ClientLogin (
is deprecated, how can we perform a programmatic authentication to Google with OAuth2?

With ClientLogin we could perform a post to
with email and password parameters and obtain the authentication token.

With OAuth2 i can't find a solution!


My app is a java background process.
I saw, following this link:, how to obtain a new access token using a refreshed token.

The problem is that I can't find a java example about how to instantiate an Analytics object (for example) to perform a query when I have a new valid access token

This is my code that returns a 401 Invalid credentials when invoke the "execute()":

public class Test {

static final String client_id = "MY_CLIENT_ID";
static final String client_secret = "MY_SECRET";
static final String appName = "MY_APP";

private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();

static String access_token = "xxxx";
static String refreshToken = "yyyyy";

public static void main (String args[]){

try {

GoogleCredential credential =
new GoogleCredential.Builder()
.setClientSecrets(client_id, client_secret).build();
Analytics analytics = Analytics.builder(HTTP_TRANSPORT, JSON_FACTORY)

Accounts accounts =;
} catch (Exception e) {

What is the problem?

Answer Source

Check the OAuth 2 flow for Installed Application:

It still requires the user to authenticate with a browser the first time, but then you can store the refresh token and use it for subsequent requests.

For alternative solutions, check the Device flow or Service Accounts, they are explained in the same documentation set.