I am creating a server side web application on google console and I have taken reference from this website https://developers.google.com/identity/protocols/oauth2/web-server Here the flow is at first it will ask for login account and password on browser and ask for the approval consent for mentioned scopes. Is there any way to eliminate the need of browser here and achieve all these things through java program, considering I know the user's credentials and providing scope's access not a security concern through code.
Asked
Active
Viewed 414 times
0
-
Your question is unclear. If you're using Google-provided User credentials to enable a user to access their data on Google's services then you've 2 choices: (1) Use the OAuth2 user flow as you're doing which cannot be short-circuited; (2) If the User is part of a Workspace domain, an admin can create a Service Account that has [domain-wide delegation of authority](https://developers.google.com/admin-sdk/directory/v1/guides/delegation) to operate on the domain's users behalf. – DazWilkin Jun 08 '22 at 15:53
1 Answers
0
If you want to automate this process you need to create you own com.google.api.client.auth.oauth2.Credential
object and .setRefreshToken
.
private static Credential getCredentials() throws IOException {
InputStream in = GmailService.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, SCOPES)
.setApprovalPrompt("auto")
.setAccessType("offline")
.build();
Credential credential = new Credential.Builder(flow.getMethod())
.setTransport(flow.getTransport())
.setJsonFactory(flow.getJsonFactory())
.setTokenServerEncodedUrl(flow.getTokenServerEncodedUrl())
.setClientAuthentication(flow.getClientAuthentication())
.setRequestInitializer(flow.getRequestInitializer())
.setClock(flow.getClock()).build();
credential.setRefreshToken("YOUR_REFRESH_TOKEN");
return credential;
}
Code was gotten from https://developers.google.com/gmail/api/quickstart/java

Serhii Leizo
- 1
- 1