【问题标题】:Gmail API: Credentials for Gmail APIGmail API:Gmail API 的凭据
【发布时间】:2015-06-19 21:11:37
【问题描述】:

这是"Java Quickstart" Gmail API 教程中给出的代码。这是我为应用程序创建凭据需要做的事情:

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);


我可以做些什么来自动化上述过程,就像在这里完成的那样,以获得进一步使用的凭证?

以下示例适用于 Google 任务。

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

【问题讨论】:

    标签: java gmail gmail-api


    【解决方案1】:
    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();
    

    【讨论】:

      【解决方案2】:

      将此应用程序的用户凭据存储在目录中。

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

      FileDataStoreFactory创建一个全局实例。

      private static FileDataStoreFactory DATA_STORE_FACTORY;
      

      在获取凭据之前实例化DATA_STORE_FACTORY,最好在静态块中。

      DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
      

      从 Google Developer 控制台下载并存储 client_secrets.json。使用以下方法获取凭据:

      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;
      }
      

      每当调用上述方法时,它都会在提供给DATA_STORE_DIR 的路径中查找StoredCredential。如果找到,则代码按原样执行。如果没有,将打开一个浏览器,要求您登录并授权您的应用程序。这样生成的凭据将存储在DATA_STORE_DIR 位置。只要StoredCredential 存在,您的应用就不会请求许可。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-02
        • 2018-07-09
        • 2015-06-03
        • 2013-06-26
        • 2020-03-02
        • 2021-04-28
        • 2013-02-22
        • 1970-01-01
        相关资源
        最近更新 更多