Ayush Gupta
Ayush Gupta

Reputation: 1717

Gmail API: Credentials for Gmail API

This is code given in the "Java Quickstart" tutorial for Gmail API. This is what I need to do to create a credential for the app:

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
    httpTransport, jsonFactory, clientSecrets, Arrays.asList(SCOPE))
    .setAccessType("online")
    .setApprovalPrompt("auto").build();

String url = flow.newAuthorizationUrl().setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
    .build();
System.out.println("Please open the following URL in your browser then type"
    + " the authorization code:\n" + url);

// Read code entered by user.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = null;
try {
   code = br.readLine();
} catch (IOException e) {
   e.printStackTrace();
}

// Generate Credential using retrieved code.
GoogleTokenResponse response = null;
try {
   response = flow.newTokenRequest(code)
           .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute();
} catch (IOException e) {
   e.printStackTrace();
}
GoogleCredential credential = new GoogleCredential()
    .setFromTokenResponse(response);


Is there something I can do to automate the above process like it is done here to get the credential for further use?

The below example is for Google Tasks.

GoogleAccountCredential credential =
   GoogleAccountCredential.usingOAuth2(this, Collections.singleton(TasksScopes.TASKS));

Upvotes: 3

Views: 2132

Answers (2)

Bilesh Ganguly
Bilesh Ganguly

Reputation: 4131

Store user credentials for this application in a directory.

private static final java.io.File DATA_STORE_DIR = new java.io.File(
        System.getProperty("user.home"), ".store/mail_credentials");

Make a global instance for FileDataStoreFactory.

private static FileDataStoreFactory DATA_STORE_FACTORY;

Instantiate DATA_STORE_FACTORY before getting credentials preferably in a static block.

DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);

Download and store the client_secrets.json from Google Developer console. Use the following method to get credentials:

public static Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in
            = GmailQuickStart.class.getResourceAsStream("/client_secrets.json");
    GoogleClientSecrets clientSecrets
            = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow
            = new GoogleAuthorizationCodeFlow.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(DATA_STORE_FACTORY)
            .setAccessType("offline")
            .build();
    Credential credential = new AuthorizationCodeInstalledApp(
            flow, new LocalServerReceiver()).authorize("user");
    System.out.println(
            "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}

Whenever the above method is called, it looks for the StoredCredential in the path provided to DATA_STORE_DIR. If it is found, then the code executes as is. If not, a browser will open which will ask you to login and authorize your app. The credentials generated as such will be stored in the DATA_STORE_DIR location. As long as the StoredCredential is present, your app won't ask for permission.

Upvotes: 1

Kiran Palaka
Kiran Palaka

Reputation: 86

GoogleCredential credential = new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(JSON_FACTORY)
            .setServiceAccountId(service_account)
            .setServiceAccountScopes(
                    Collections.singleton("https://mail.google.com/"))
            // .setServiceAccountPrivateKeyFromP12File(new
            // File(certLocation))
            .setServiceAccountPrivateKey(serviceAccountPrivateKey)
            .setServiceAccountUser(senderid).build();

Upvotes: 1

Related Questions