代表用户创建谷歌日历

问题描述

我正在开发一个 java Springboot 后端应用程序。 其中我有多个用户,我需要为他们创建日历事件并使用他们的 gmail id 发送邮件。我只能使用单个用户的凭据来验证 Google Api

有什么方法可以使用客户端的 gmail id 在邮件上创建日历事件,而无需每次使用 Google Api 从 UI 获得客户端的同意?

如果有一种方法可以在无需与 UI 交互的情况下使用 Google Api 进行身份验证,也请提供建议。

解决方法

Google 日历数据是私人用户数据,为了在用户日历上创建一个偶数,您需要拥有该日历的用户的许可。

为此,我们使用称为 Oauth2 的东西,使用 Oauth2,您的应用程序将请求用户访问那里的数据的权限,授权服务器将返回给您一个令牌,授予您代表用户访问 api 的权限。

未经所有者授予您访问权限,您无法访问私人用户数据。

无需每次使用 google api 从 UI 获得客户端的同意

现在您可以做的一件事是请求用户离线访问,如果用户授予您离线访问权限,您将获得一个刷新令牌,您可以在以后使用它来请求新的访问令牌。使用访问令牌,您可以更改用户日历,而无需他们实际运行您的应用程序。

DATA_STORE_DIR 用于用户存储

这段代码应该很接近,它从谷歌分析的示例中略有改动,但应该向您展示如何使用 DATA_STORE_DIR 来存储用户凭据以备后用。

/**
 * A simple example of how to access the Google calendar API.
 */
public class HelloCalendar {
  // Path to client_secrets.json file downloaded from the Developer's Console.
  // The path is relative to HelloCalendar.java.
  private static final String CLIENT_SECRET_JSON_RESOURCE = "client_secrets.json";

  // The directory where the user's credentials will be stored.
  private static final File DATA_STORE_DIR = new File(
      System.getProperty("user.home"),".store/hello_calendar");

  private static final String APPLICATION_NAME = "Hello Calendar";
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
  private static NetHttpTransport httpTransport;
  private static FileDataStoreFactory dataStoreFactory;

  public static void main(String[] args) {
    try {
      Calendar service = initializeCalendar();

      // do stuff here 
      printResponse(response);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


  /**
   * Initializes an authorized calendar service object.
   *
   * @return The Calendar service object.
   * @throws IOException
   * @throws GeneralSecurityException
   */
  private static Calendar initializeCalendar() throws GeneralSecurityException,IOException {

    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

    // Load client secrets.
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,new InputStreamReader(Calendar.class
            .getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE)));

    // Set up authorization code flow for all authorization scopes.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
        .Builder(httpTransport,JSON_FACTORY,clientSecrets,CalendarScopes.all()).setDataStoreFactory(dataStoreFactory)
        .build();

    // Authorize.
    Credential credential = new AuthorizationCodeInstalledApp(flow,new LocalServerReceiver()).authorize("THISISTHEUSERNAME");
    // Construct the Analytics Reporting service object.
    return new Calendar.Builder(httpTransport,credential)
        .setApplicationName(APPLICATION_NAME).build();
  }