问题描述
我有简单配置的应用
spring.security.oauth2.client.registration.google.clientId=xyz
spring.security.oauth2.client.registration.google.clientSecret=xyz
spring.security.oauth2.client.registration.google.scope=email,profile,openid,https://www.googleapis.com/auth/calendar,https://www.googleapis.com/auth/spreadsheets
我使用 http://localhost:8080/oauth2/authorization/google 登录并正常保存到谷歌日历。
获取访问令牌看起来像:
private String getAccesstoken() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String accesstoken = null;
if (authentication.getClass().isAssignableFrom(OAuth2AuthenticationToken.class)) {
OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
String clientRegistrationId = oauthToken.getAuthorizedClientRegistrationId();
OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient(
clientRegistrationId,oauthToken.getName());
accesstoken = client.getAccesstoken().getTokenValue();
}
return accesstoken;
}
OAuth2AuthorizedClient
包含刷新令牌。
但 1 小时后访问令牌过期,我不知道如何刷新它。无需重新登录。
https://developers.google.com/calendar/v3/errors#401_invalid_credentials 说
使用长期存在的刷新令牌获取新的访问令牌。
我找到了这个 Spring Google OAuth2 With Refresh Token 但对我不起作用。
你能帮我吗?提前致谢。
解决方法
感谢 DaImTo 的提示。
我从
更改了我的凭据使用 Credential credential = new GoogleCredential().setAccessToken(tokenUtils.getAccessToken());
到
private Calendar getClient() throws GeneralSecurityException,IOException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
Credential credential = new GoogleCredential.Builder()
.setJsonFactory(JSON_FACTORY)
.setTransport(httpTransport)
.setClientSecrets(clientId,clientSecret)
.build()
.setAccessToken(tokenUtils.getAccessToken())
.setRefreshToken(tokenUtils.getRefreshToken());
return new Calendar.Builder(httpTransport,JSON_FACTORY,credential)
.setApplicationName("appname").build();
}
它有效!
但只有在设置 prompt
且值为 select_account
或 consent
时,应用才会接收刷新令牌。
使用值 none
或不使用 prompt
刷新令牌始终为空 (access_type=offline
)。
它也不是用户友好的,因为应用程序用户每次都必须选择谷歌帐户...
你知道一些解决方法吗?