[英]Spring 5, OAuth2 with Google refresh access token after 401 return
我有简单的配置应用程序
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但对我不起作用。
在 401 之后也有重新登录消息,但它对用户不友好。
你可以帮帮我吗? 提前致谢。
感谢 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();
}
它有效!
但是只有当设置了带有值select_account
或consent
的prompt
时,应用程序才会收到刷新令牌。 值为none
或没有prompt
Refresh Token 始终为 null ( access_type=offline
)。
它也不是用户友好的,因为应用程序用户每次都必须选择谷歌帐户......
你知道一些解决方法吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.