如何控制谷歌 API 访问的令牌响应到期时间



我在延长谷歌访问令牌有效性的标准一小时时遇到问题。我的代码的一部分是获得用户的授权,根据Google建议使用GoogleAuthorizationCodeFlow。这工作正常,并给了我一个令牌响应,我坚持在用户未连接的应用程序的其他部分使用。

根据 Google 文档,我认为流中的"offline"访问类型将使 TokenResponse 在用户不撤销它的情况下可用。但显然,当我在用户授权后使用此 TokenReponse 时,它工作正常,但是当我在一个多小时后使用它时,我收到 Google 发回的"无效凭据"。

以下是在用户授权后创建令牌响应的代码:

private HttpTransport HTTP_TRANSPORT;
private JacksonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static GoogleAuthorizationCodeFlow flow;
@PostConstruct
public void init() {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    } catch (GeneralSecurityException | IOException e) {
        logger.info(String.format("Raised Exception while getting GoogleNetHttpTransport : %s", e.getMessage()));
        e.printStackTrace();
    }
    flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, APP_ID, APP_SECRET,
            Collections.singleton(CalendarScopes.CALENDAR_READONLY)).setAccessType("offline").build();
}
@RequestMapping(value = Uris.GOOGLERD)
public ModelAndView googleCallBack(HttpServletRequest request, @RequestParam(value = "state", required = false) String state,
        @RequestParam(value = "code", required = false) String code,
        @RequestParam(value = "error", required = false) String error, Model model) {
    DynSubscriber dynSubscriber = (DynSubscriber) request.getSession().getAttribute("dynSubscriber");
    ModelAndView toReturn = new ModelAndView("confirmation");
    toReturn.addObject("buttonLabel", "Accueil");
    try {
        AuthorizationCodeTokenRequest tokenRequest = flow.newTokenRequest(code);
        TokenResponse tr = tokenRequest.setRedirectUri(request.getRequestURL().toString()).execute();

        // Json Conversion of Token Response for future use
        StringWriter jsonTrWriter = new StringWriter();
        JsonGenerator generator = JSON_FACTORY.createJsonGenerator(jsonTrWriter);
        generator.serialize(tr);
        generator.flush();
        generator.close();

        //Persists google access info 
        dynSubOp.setSPConnexionInfo(dynSubscriber, jsonTrWriter.toString(), DynServiceProviderType.GOOGLECAL);
        toReturn.addObject("message","Agenda Google autorisé");
    } catch (IOException | DynServicesException e) {
        logger.error(String.format("Exception raised in googleCallBack for subscriber %s : %s", dynSubscriber.buildFullName(), e.getMessage()),e);
        toReturn.addObject("message", "Problème lors du processus d'autorisation google");
    }
    return toReturn;
}
}

这是使用此令牌响应的离线代码:

private com.google.api.services.calendar.Calendar calendarConnection;

public DynGoogleCalendarRetriever(String subid, String connectionInformation)
        throws CalendarConnectionNotAuthorizedException {

    TokenResponse tr;
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        tr = JSON_FACTORY.fromString(connectionInformation, TokenResponse.class);
        Credential c = new GoogleCredential().setFromTokenResponse(tr);
        calendarConnection = new com.google.api.services.calendar.Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, c)
                .build();
    } catch (IOException | GeneralSecurityException e) {
        logger.error(String.format("Failure creating the credentials for subscriber id %s", subid), e);
        throw new CalendarConnectionNotAuthorizedException(String.format(
                "Failure creating the credentials for subscriber id %s", subid), e);
    }

}

看起来这已经在另一个 SO 问题中得到了回答。要获取启用所需内容的刷新令牌,我需要使用 approval_prompt=force 参数 ( builder.setApprovalPrompt("force") ) 构建流

根据注释,这需要在流初始化中完成的脱机访问。

但是补充:尽管我从Google文档中复制并粘贴了离线代码(可能是旧版本),但我问题中的离线代码不起作用。凭据需要使用其生成器对象。

这是功能齐全的离线代码:

    TokenResponse tr;
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        tr = JSON_FACTORY.fromString(connectionInformation, TokenResponse.class);
        Credential c = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
                .setClientSecrets(APP_ID, APP_SECRET).build().setFromTokenResponse(tr);
        calendarConnection = new com.google.api.services.calendar.Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, c)
                .build();
    } catch (IOException | GeneralSecurityException e) {
        logger.error(String.format("Failure creating the credentials for subscriber id %s", subid), e);
        throw new CalendarConnectionNotAuthorizedException(String.format(
                "Failure creating the credentials for subscriber id %s", subid), e);
    }

相关内容

  • 没有找到相关文章

最新更新