【问题标题】:Locally works, fails on server : Google calendar API本地工作,在服务器上失败:谷歌日历 API
【发布时间】:2021-12-29 01:35:14
【问题描述】:

在现有的基于 Java 的 Spring Boot 应用程序中,我集成了 Google 日历 API。在我当地,它有效。在开发服务器上,我看到要在浏览器中打开的 URL 是:

https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=xxx.apps.googleusercontent.com&redirect_uri=http://localhost:8080/Callback&response_type=code&scope=https://www.googleapis.com/auth/calendar.events

重定向 uri 是 http://localhost:8080/Callback 而不是 https://dev.myserver.in/Callback,这会导致无效请求

即使我手动更正 URI 并在浏览器中过去,它也会显示 404。

我已经创建了服务帐户并为 localhost 和我的开发服务器提供了重定向 uri,并且我在我的代码中使用了与 credential.json 文件相同的文件。

以下是代码sn-ps

private Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        // Load client secrets.
        InputStream in = GoogleCalendarServiceImpl.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));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY,
                clientSecrets, SCOPES)
                        .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(tokensDirectoryPath)))
                        .setAccessType("offline")
                        .build();
        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build(); //.Builder().setPort(localServerReceiverPort).build();
        return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    }

在这里使用它:

public void createEvent(CreateEventRequest request) throws GeneralSecurityException, IOException {

    // Build a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Calendar service = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME).build();

    Event event = createEvent(request);
    String calendarId = "primary";
    Event createdEvent = service.events().insert(calendarId, event).execute();

    log.info("Event successfully created! : {} ", createdEvent.getHtmlLink());

}

这里是配置:

private static final String APPLICATION_NAME = "Calendar";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String CREDENTIALS_FILE_PATH = "/credential.json";
    
    @Value("${google.calendar.tokens.directory.path}")
    private String tokensDirectoryPath
    
    
    /**
     * Global instance of the scopes required by this quickstart. If modifying these
     * scopes, delete your previously saved tokens/ folder.
     */
    private static final List<String> SCOPES = Collections.singletonList(CalendarScopes.CALENDAR_EVENTS);

【问题讨论】:

    标签: java spring-boot google-oauth google-calendar-api google-api-java-client


    【解决方案1】:

    你正在使用

    new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
    

    这适用于已安装的应用程序。已安装的应用程序使用 localhost 作为重定向 uri。

    对于 Web 服务器 aplciston,您应该使用 GoogleAuthorizationCodeFlow

    public class CalendarServletSample extends AbstractAuthorizationCodeServlet {
    
      @Override
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws IOException {
        // do stuff
      }
    
      @Override
      protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
        GenericUrl url = new GenericUrl(req.getRequestURL().toString());
        url.setRawPath("/oauth2callback");
        return url.build();
      }
    
      @Override
      protected AuthorizationCodeFlow initializeFlow() throws IOException {
        return new GoogleAuthorizationCodeFlow.Builder(
            new NetHttpTransport(), GsonFactory.getDefaultInstance(),
            "[[ENTER YOUR CLIENT ID]]", "[[ENTER YOUR CLIENT SECRET]]",
            Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(
            DATA_STORE_FACTORY).setAccessType("offline").build();
      }
    
      @Override
      protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
        // return user ID
      }
    }
    
    public class CalendarServletCallbackSample extends AbstractAuthorizationCodeCallbackServlet {
    
      @Override
      protected void onSuccess(HttpServletRequest req, HttpServletResponse resp, Credential credential)
          throws ServletException, IOException {
        resp.sendRedirect("/");
      }
    
      @Override
      protected void onError(
          HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse)
          throws ServletException, IOException {
        // handle error
      }
    
      @Override
      protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
        GenericUrl url = new GenericUrl(req.getRequestURL().toString());
        url.setRawPath("/oauth2callback");
        return url.build();
      }
    
      @Override
      protected AuthorizationCodeFlow initializeFlow() throws IOException {
        return new GoogleAuthorizationCodeFlow.Builder(
            new NetHttpTransport(), GsonFactory.getDefaultInstance()
            "[[ENTER YOUR CLIENT ID]]", "[[ENTER YOUR CLIENT SECRET]]",
            Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(
            DATA_STORE_FACTORY).setAccessType("offline").build();
      }
    
      @Override
      protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
        // return user ID
      }
    }
    

    还要确保您在谷歌云控制台上创建了 Web 应用程序凭据,而不是安装应用程序凭据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-24
      • 2015-04-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2016-11-01
      • 2013-05-11
      • 1970-01-01
      相关资源
      最近更新 更多