Currently I need to use the Gmail API to check the labels of newly arrived emails. It was perfect on my laptop, that I need to manually authorize for the first time starting the program(Java), and subsequent calls don't require user interactions.
This program is a quickstart sample code from Gmail API https://developers.google.com/gmail/api/quickstart/java
Now I need this program to run on the server so that I can monitor the landing status. After dozens of attempts, the server was unable to detect the tokens I uploaded from my laptop and kept asking me to open a redirecting url to authorize.
gmailLog.info("getCredentials start!");
InputStream in = GmailAPI.class.getResourceAsStream("/credentials.json");
if (in == null) {
gmailLog.error("null input stream, credentials missing");
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new File("tokens")))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
The authorization happens on the last line of the code. Then a tokens folder is generated, please click this link to see the file structure.
As you can see, the tokens folder is placed under the root path. I copied the tokens folder to the server at the same location, but still I was asked to redirect. I wonder maybe this is because the StoredCredential file has my machine's information so it doesn't match the server machine.
Does this mean I can never do this on the server without user input? thank you. Also if a GSuite account is absolutely needed, I'm willing to pay and become an enterprise user.