如何在google oauth2.0中移除对浏览器的依赖



我正在创建一个服务器端web应用程序在谷歌控制台,我已经从这个网站https://developers.google.com/identity/protocols/oauth2/web-server这里的流程是首先它会要求登录帐户和密码在浏览器上,并要求批准同意提到的范围。考虑到我知道用户的凭据,并且通过代码提供作用域的访问而不是安全问题,有没有办法在这里消除对浏览器的需要并通过java程序实现所有这些事情?

如果你想自动化这个过程,你需要创建你自己的com.google.api.client.auth.oauth2.Credential对象和.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;
}

代码来自https://developers.google.com/gmail/api/quickstart/java

最新更新