将 Spring Security 配置迁移到 Spring Cloud 2022.0.4

Pet*_*zov 7 java spring-security spring-boot spring-oauth2

我想将此 Spring 安全配置迁移到最新的 Spring Cloud:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

public class DefaultSecurityConfig extends ResourceServerConfigurerAdapter {

  @Autowired
  private ResourceServerProperties resource;

  @Autowired
  private CustomUserDataAuthenticationConverter customUserDataAuthenticationConverter;

  public DefaultSecurityConfig() {
  }

  @Override
  public void configure(final HttpSecurity http) throws Exception {

    http.authorizeRequests()
        .antMatchers("/configuration/**",)
        .permitAll();

    http.authorizeRequests().antMatchers("/**").authenticated();

    final OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPoint =
        new CustomOAuth2AuthenticationEntryPoint();

    http.exceptionHandling().authenticationEntryPoint(oAuth2AuthenticationEntryPoint);
  }

  @Override
  public void configure(final ResourceServerSecurityConfigurer resources) {
    resources.tokenServices(tokenServices());
    resources.resourceId(resource.getResourceId());
  }

  private TokenStore customTokenStore() {
    return new JwtTokenStore(accessTokenConverter());
  }

  private JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new NonValidatingAccessTokenConverter();
    converter.setAccessTokenConverter(customAccessTokenConverter());
    return converter;
  }

  private DefaultTokenServices tokenServices() {
    DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
    defaultTokenServices.setTokenStore(customTokenStore());
    return defaultTokenServices;
  }

  private DefaultAccessTokenConverter customAccessTokenConverter() {
    DefaultAccessTokenConverter tokenConverter = new DefaultAccessTokenConverter();
    tokenConverter.setUserTokenConverter(customUserDataAuthenticationConverter);
    return tokenConverter;
  }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我迁移了部分代码,但有几个问题尚不清楚:

  1. 实现 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure' 已从spring.dependency.management包中删除。应该用什么包来代替它?

  2. ResourceServerConfigurerAdapter已弃用。如何更换?

  3. OAuth2AuthenticationEntryPoint已弃用。如何更换?

相应地迁移代码的正确方法应该是什么?

And*_*isa 3

官方文档中如何描述spring-security-oauth-reaches-end-of-life

还有我们在评论中讨论的方式,您将拥有一个授权服务器Keycloak作为具有 oAuth2.0 和 Oidc 连接的身份提供者。

您的迁移代码将包含以下步骤:

在您的案例中将当前资源服务器替换为 JWT 作为承载令牌

Gradle/Maven 配置:

摇篮:

  implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '3.1.2'

  implementation group: 'org.springframework.boot', name: 'spring-boot-starter-oauth2-resource-server', version: '3.1.2'
Run Code Online (Sandbox Code Playgroud)

行家:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
    <version>3.1.2</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    <version>3.1.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

在 application.yml 文件中,您应该提供下一个路径:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: 
          jwk-set-uri: 
Run Code Online (Sandbox Code Playgroud)

您可以在 Keycloak 端的/.well-known/openid-configuration路径中找到该值。

安全配置层的外观如下:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

     
  @Bean
  public AuthenticationManager authenticationManager(
      AuthenticationConfiguration authenticationConfiguration) throws Exception {
    return authenticationConfiguration.getAuthenticationManager();
  }

  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity request) throws Exception {

    request.cors(corsConfigurer -> corsConfigurer.configurationSource(yourCustomCorsConfiguration))
        .csrf(AbstractHttpConfigurer::disable);

    request.headers(http -> http.frameOptions(FrameOptionsConfig::sameOrigin));
    request.sessionManagement(sessionAuthenticationStrategy ->
        sessionAuthenticationStrategy.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

    request.authorizeHttpRequests(requestMatcherRegistry -> {

      requestMatcherRegistry.anyRequest().authenticated();
    });

    request.oauth2ResourceServer(httpSecurityOAuth2ResourceServerConfigurer ->
            httpSecurityOAuth2ResourceServerConfigurer.jwt(
                token -> token.jwtAuthenticationConverter(myConverter())));

    return request.build();
  }

@Bean
public JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
}

}
Run Code Online (Sandbox Code Playgroud)

你还应该看看oauth2-clientspring-authorization-server