Stored Credential from Google API to be reused using Java
Asked Answered
F

2

12

I have successfully authorized my desktop application. It stores a file called StoredCredential. In order to not have to keep doing the copy URL into browser, accept, etc., steps every time I run the app, I want to use the credentials that I already have stored.

My code so far:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
    httpTransport,
    JSON_FACTORY,
    CLIENT_ID,
    CLIENT_SECRET,
    SCOPE)
    .setDataStoreFactory(dataStoreFactory)
    .setApprovalPrompt("auto").setAccessType("offline").build();
//
System.out.println("flow success");     

String url = flow
    .newAuthorizationUrl()
    .setRedirectUri(REDIRECT_URI) 
    .build();

System.out.println("Please open the following URL in your browser then "
    + "type the authorization code:");

System.out.println("  " + url);

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String code = br.readLine();

GoogleTokenResponse tokenResponse
    = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();

GoogleCredential credential = new GoogleCredential
    .Builder()
    .setTransport(new NetHttpTransport())
    .setJsonFactory(new JacksonFactory())
    .setClientSecrets(CLIENT_ID, CLIENT_SECRET)
    .addRefreshListener(new CredentialRefreshListener() {
            @Override
            public void onTokenResponse(
                Credential credential,
                TokenResponse tokenResponse) throws IOException {

                System.out.println("Token Refreshed Succesfully");
            }

            @Override
            public void onTokenErrorResponse(
                Credential credential,
                TokenErrorResponse tokenErrorResponse) throws IOException {

                System.out.println("ERROR WITH TOKEN WTF?");
                }})
     .build();

How do I read the stored credential and bypass the command line prompt?

I was thinking something like:

if (stored cred exists) { 
    try  {
        // use 
    } catch  {
        // prompt the user
    }
}
Fez answered 8/11, 2013 at 14:17 Comment(2)
Essentially is there a way to say GoogleCredential credential = new GoogleCredential.Builder().getThingFromFileFez
I posted an answer here https://mcmap.net/q/1009136/-authorization-to-google-client that I think addresses what you are after with more detailBoylston
U
15

You can create GoogleCredential object from stored credentials like this:

GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(new NetHttpTransport())
        .setJsonFactory(new JacksonFactory())
        .setClientSecrets("client_id", "client_secret")
        .build();

credential.setAccessToken("access_token");
Uncommonly answered 12/11, 2013 at 13:43 Comment(1)
How does it know where to load the refresh-token or StroredCredential from?Conservative
L
2
public Credential buildEmptyCredential() {
    Credential credential = null;
    try {
        credential = new GoogleCredential.Builder()
            .setClientSecrets(Utils.getClientCredential())
            .setTransport(new NetHttpTransport())
            .setJsonFactory(Constant.JSON_FACTORY)
            .build();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return credential;
}

buildEmptyCredential()
    .setRefreshToken(storedCredential.getRefreshToken())
    .setAccessToken(storedCredential.getAccessToken())
    .setExpirationTimeMilliseconds(storedCredential.getExpirationTimeMilliseconds());
Luciano answered 26/2, 2015 at 10:38 Comment(1)
You could add some explanation to this answerZibeline

© 2022 - 2024 — McMap. All rights reserved.