我的Spring客户端应用程序如何访问诸如GoogleinSpringSecurity5提供的刷新令牌?
很简单的问题。远程授权服务器(例如Google)发送刷新令牌,我想使用它。在Security 5中持久化和检索它的最佳方法是什么?
这个答案、这个问题和这种千篇一律的联系似乎描述了一种不再兼容的方法,因为Oauth2在Security 5中成为了一流的公民。
上下文:
刷新令牌允许客户端应用程序在用户会话过期后继续访问资源。根据谷歌的文档,刷新令牌应该是持久的:
应用程序应该存储刷新令牌以供将来使用,并使用该访问令牌访问Google。
Spring安全性使访问令牌以OAuth2AuthenticationToken的形式广泛可用,但其中不包括刷新令牌。
刷新令牌在OidcUserService (或重写它的类)中也不可用,因为public OidcUser loadUser(OidcUserRequest userRequest)没有访问刷新令牌的权限。这是一个令人沮丧的问题,因为使用自定义类覆盖OidcUserService将很好,该类可以创建/检索用户的OIDC用户详细信息,并同时保存相关的刷新令牌。
OAuth2LoginAuthenticationFilter将刷新令牌保存在ClientRegistrationRepository中:
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
authenticationResult.getClientRegistration(),
oauth2Authentication.getName(),
authenticationResult.getAccessToken(),
authenticationResult.getRefreshToken());
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, oauth2Authentication, request, response);默认的实现将令牌保存在瞬态内存中,这不适合于分布式应用程序或在重新启动时持久化。
似乎有一个带有JdbcOauth2AuthorizedClientService的docs最近增加了和一个图式,暗示可能有用,但是没有提供配置它或使用它来检索刷新令牌的示例。
那么,客户端应用程序如何在Security 5中持久化并访问刷新令牌呢?
发布于 2020-05-02 19:35:30
JdbcOauth2AuthorizedClientService确实适合您的用例。配置非常简单。首先,您需要将此表添加到数据库中:
CREATE TABLE oauth2_authorized_client (
client_registration_id varchar(100) NOT NULL,
principal_name varchar(200) NOT NULL,
access_token_type varchar(100) NOT NULL,
access_token_value blob NOT NULL,
access_token_issued_at timestamp NOT NULL,
access_token_expires_at timestamp NOT NULL,
access_token_scopes varchar(1000) DEFAULT NULL,
refresh_token_value blob DEFAULT NULL,
refresh_token_issued_at timestamp DEFAULT NULL,
created_at timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL,
PRIMARY KEY (client_registration_id, principal_name)
);然后,配置JdbcOauth2AuthorizedClientService bean:
@Bean
public OAuth2AuthorizedClientService oAuth2AuthorizedClientService
(JdbcOperations jdbcOperations, ClientRegistrationRepository clientRegistrationRepository) {
return new JdbcOAuth2AuthorizedClientService(jdbcOperations, clientRegistrationRepository);
}请注意,当前的实现有一个错误,它将在几天后到期的security版本5.3.2中解决。
https://stackoverflow.com/questions/60822062
复制相似问题