oauth-2.0 如何在google oauth2.0中删除获得响应的浏览器依赖性

f3temu5u  于 2022-10-31  发布在  Go
关注(0)|答案(1)|浏览(189)

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

xkftehaa

xkftehaa1#

如果你想自动化这个过程,你需要创建你自己的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获取代码

相关问题