Java Spring5,OAuth2在401返回后使用Google刷新访问令牌
我有一个简单的配置应用程序Java Spring5,OAuth2在401返回后使用Google刷新访问令牌,java,spring-security,google-oauth,google-calendar-api,spring-oauth2,Java,Spring Security,Google Oauth,Google Calendar Api,Spring Oauth2,我有一个简单的配置应用程序 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/au
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小时后,访问令牌过期,我不知道如何刷新它。没有重新登录
说
使用长寿命刷新令牌获取新的访问令牌
我找到了这个,但不适合我
A也会在401之后重新登录消息,但它不是用户友好的
你能帮我吗?提前谢谢。谢谢DaImTo的提示 我从更改了凭据使用
Credential credential = new GoogleCredential().setAccessToken(tokenUtils.getAccessToken());
到
而且它有效
但只有当设置了值为“选择帐户”或“同意”的“提示”时,应用程序才会收到刷新令牌。
有值none
或无提示时,刷新令牌始终为空(access\u type=offline
)
它对用户也不友好,因为应用程序用户每次都必须选择google帐户
你知道一些解决方法吗?我对Java帮助不大,但是如果你检查一下这个示例,看看它是如何使用FileDataStoreFactory的,如果你请求离线访问,你会得到一个刷新令牌,GoogleAuthorizationCodeFlow可以在需要时使用它来加载对en的新访问。你尝试过遵循日历API吗,我解决了我的问题如下。要使用OAuth2 Google进行身份验证,我使用Spring内置机制。这是recivies访问令牌和刷新令牌,然后我使用它们通过谷歌库连接到谷歌日历。可能是因为本地主机。。。
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();
}