获取空刷新令牌

Pap*_*cel 2 oauth google-api google-api-java-client

我正在使用 google-api-java-client 版本 1.8-beta 对 Google 帐户进行 oAuth2 身份验证。一切都很好,直到我得到 GoogleTokenResponse 对象,它有访问令牌但没有刷新令牌。要构建请求 url,我使用以下方法:

...
    googleAuthenticationUrl = new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, callBackUrl, scopes).build();
...
Run Code Online (Sandbox Code Playgroud)

获取请求令牌时,我将其与此行中的访问令牌交换:

...
GoogleTokenResponse tokenResponse =  new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(), CLIENT_ID, CLIENT_SECRET, request.getParameter(CODE_URL_PARAM), callBackUrl).execute();
...
Run Code Online (Sandbox Code Playgroud)

返回的 GoogleTokenResponse 对象不包含刷新令牌:

{"access_token":"ya29.AH..etc...9-Y","expires_in":3600,"token_type":"Bearer"}
Run Code Online (Sandbox Code Playgroud)

你能解释一下这个问题吗?非常感谢您的帮助!

Pap*_*cel 5

在构建请求 Url 时,您应该设置访问类型:

requestUrl = new GoogleAuthorizationCodeRequestUrl(googleClientId, callBackUrl, scopes)
    .setApprovalPrompt("force") // needed if user already granted permission
    .setAccessType("offline")
    .build();
Run Code Online (Sandbox Code Playgroud)

本页所述,建议设置此参数:

[...] 我们建议您将 access_type 参数显式设置为 offline,因为我们预计在引入 online 值时,它将作为默认行为。这可能会导致您的应用程序发生意外更改,因为它会影响您的应用程序被允许刷新访问令牌的方式。通过将参数值显式设置为离线,您可以避免应用程序功能发生任何变化。[...]