Spring Secuity 5:坚持和访问Oauth2刷新令牌。

问题描述 投票:0回答:1

我的Spring Boot客户端应用程序如何访问Spring Security 5中Google等提供的刷新令牌?

很简单的问题。远程授权服务器(如 Google)发送了一个刷新令牌,我想使用它。在Spring Security 5中坚持和检索它的最佳方法是什么?

似乎 本回答, 这个问题这条外链 描述一种方法,自从Oauth2成为Spring Security 5的一级公民后,这种方法就不再兼容了。

上下文。

刷新令牌允许客户端应用程序在用户会话过期后继续访问资源。根据谷歌的文档,刷新令牌应该是持久的。

应用程序应该存储刷新令牌供将来使用,并使用访问令牌来访问Google API。

春天的安全性使得 令牌 的形式广泛存在。OAuth2AuthenticationToken但那里不包括刷新令牌。

刷新令牌也不包含在 OidcUserService (或一个覆盖它的类),因为 public OidcUser loadUser(OidcUserRequest userRequest) 不能访问刷新令牌。这是一个令人沮丧的问题,因为如果能用一个自定义类覆盖OidcUserService,从用户的OIDC用户详情中创建检索用户,那就更好了。并同时保存其相关的刷新令牌。.

OAuth2LoginAuthenticationFilter 将刷新令牌保存在客户端注册库中。

OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
    authenticationResult.getClientRegistration(),
    oauth2Authentication.getName(),
    authenticationResult.getAccessToken(),
    authenticationResult.getRefreshToken());

this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, oauth2Authentication, request, response);

默认的实现将token保存在瞬时内存中,这不适合分布式应用或在重启时持续存在。

似乎有一个 JdbcOauth2AuthorizedClientService,与 最近添加的文档和a 示意图 它可能很有用,但没有提供配置它或使用它检索刷新令牌的例子。

那么,客户端应用程序如何在Spring Security 5中持久化并访问刷新令牌?

spring-security oauth-2.0 spring-security-oauth2 refresh-token
1个回答
0
投票

JdbcOauth2AuthorizedClientService 确实适合您的用例。首先,你需要将这个表添加到你的数据库中,然后,配置远程授权服务器(如Google)。

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);
}

请注意,目前的实现有一个bug,将在几天后的5.3.2版spring -security中解决。

© www.soinside.com 2019 - 2024. All rights reserved.