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

时间:2013-12-19 08:47:14

标签: google-api google-oauth google-oauth-java-client

对于google访问令牌的有效性,我有一个小时延长标准的问题。 我的代码的一部分是根据Google推荐使用GoogleAuthorizationCodeFlow从用户获得授权。这工作正常,并给我一个TokenResponse,我坚持在用户未连接的应用程序的其他部分使用。

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

以下是用户授权后创建TokenResponse的代码:

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

以下是使用此TokenReponse的离线代码:

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


}

1 个答案:

答案 0 :(得分:0)

this other SO question中已经回答了这个问题。 要获得支持我想要的刷新令牌,我需要使用approval_prompt = force参数(builder.setApprovalPrompt("force"))构建流程

根据评论,这需要在流初始化中完成离线访问。

但补充:我的问题中的离线代码不能正常工作,尽管我从谷歌文档中复制并粘贴了它(可能是旧版本)。凭证需要使用其Builder对象。

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

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