Spring 5整合Google OAuth2时401状态下如何免重登刷新access token
应用基础配置
搭建了配置简单的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/auth/calendar,https://www.googleapis.com/auth/spreadsheets
基础运行流程
通过http://localhost:8080/oauth2/authorization/google端点完成Google账号授权登录后,可正常实现数据写入Google日历的功能。
现有Access Token获取实现
当前项目从安全上下文读取已认证用户的授权信息,拉取存储的授权客户端对象获取access token,代码逻辑如下:
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对象中可以读取到对应的refresh token,但Google颁发的access token仅1小时有效期,过期后无法自动完成token刷新。 - 期望实现token自动刷新的全流程无需引导用户重新登录;当前仅能在调用Google接口返回401异常时引导用户重新授权,用户体验较差。
- 根据Google日历官方错误文档的说明:
需使用长有效期的refresh token获取新的access token。
- 参考了StackOverflow上Google OAuth2刷新token的相关公开实现方案,但在当前项目场景下无法生效,需要可落地的实现指导。
内容的提问来源于stack exchange,提问作者wojek
相关产品推荐
相关产品推荐

