代表用户创建 google 个日历

Create google calendar on behalf of user

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

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

如果有一种方法可以通过身份验证来使用 google api 而无需与 UI.

交互,也请提出建议

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

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

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

without having to get consent from the client from the UI each time with google api

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

DATA_STORE_DIR 用于用户存储

这段代码应该是接近的,它与 google 分析的示例稍有改动,但应该向您展示如何使用 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, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
  }