我正在尝试通过
WebClient
保存刷新令牌以在 JdbcOAuth2AuthorizedClientService
中自动续订来实现 Spring OAuth2。
当我第一次使用 Google 提示授予访问权限时,令牌会完美地存储为授予访问权限的
oauth2_authorized_client
的 principal_name
表中的一行,比如说 [电子邮件受保护]。
稍后,当我想在计划任务中使用存储的 access_token (无用户交互)时,我可以像这样获取它并将其注入我的
webClient
:
private final OAuth2AuthorizedClientService authorizedClientService;
// ...
OAuth2AuthorizedClient authorizedClient = authorizedClientService.loadAuthorizedClient("google", "[email protected]");
return webClient.get()
.uri(CALENDAR_URL, uriBuilder ->
uriBuilder.path("/calendars/primary/events")
.queryParam("key", API_KEY)
.build())
.attributes(oauth2AuthorizedClient(authorizedClient))
.retrieve()
.bodyToMono(String.class);
这次过期的令牌会自动更新(万岁!),但由于某种原因,它作为新行存储在数据库表中,其中
principal_name
为 anonymousUser 而不是 [email protected]。这是为什么?
这是我的 WebClient 配置:
@Bean
public OAuth2AuthorizedClientService oAuth2AuthorizedClientService(JdbcOperations jdbcOperations,
ClientRegistrationRepository clientRegistrationRepository) {
return new JdbcOAuth2AuthorizedClientService(jdbcOperations, clientRegistrationRepository);
}
@Bean
public WebClient webClient(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientService authorizedClientService) {
AuthorizedClientServiceOAuth2AuthorizedClientManager manager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientService);
manager.setAuthorizedClientProvider(new DelegatingOAuth2AuthorizedClientProvider(
new RefreshTokenOAuth2AuthorizedClientProvider(),
new ClientCredentialsOAuth2AuthorizedClientProvider()));
ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2 = new ServletOAuth2AuthorizedClientExchangeFilterFunction(
manager);
oauth2.setDefaultClientRegistrationId("google");
return WebClient.builder()
.filter(oauth2)
.apply(oauth2.oauth2Configuration())
.build();
}
我今天遇到了这个问题,我最终创建了自己的 oauth2AuthorizationSuccessHandler 将令牌保存到我的数据库中正确的授权客户端。
您最终是如何解决这个问题的?通过更新 securityContextHolder?