Spring安全迁移指南5

ymdaylpp  于 2022-10-05  发布在  Spring
关注(0)|答案(1)|浏览(187)

我有多模块Maven项目Spring Boot 2.3.1 RELEASE,在那里我使用了Spring安全性,而不是OAuth 2.0。我的一个模块包含安全配置:

授权服务器配置

@Configuration
@EnableAuthorizationServer //deprecated
public class AuthorizationServerOAuth2Config extends AuthorizationServerConfigurerAdapter { //deprecated

    private static final String SINGING_KEY = "";
    private static final String CLIENT_ID = "";
    private static final String CLIENT_SECRET = "";
    private static final String[] AUTHORIZED_GRANT_TYPES = {"password", "refresh_token"};
    private static final String[] SCOPES = {"read", "write"};

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) { //deprecated
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception { //deprecated

        clients.inMemory()
                .withClient(CLIENT_ID)
                .secret(passwordEncoder.encode(CLIENT_SECRET))
                .authorizedGrantTypes(AUTHORIZED_GRANT_TYPES)
                .scopes(SCOPES)
                .accessTokenValiditySeconds(1800)
                .refreshTokenValiditySeconds(9600);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) { //deprecated

        endpoints
                .tokenStore(tokenStore())
                .authenticationManager(authenticationManager)
                .accessTokenConverter(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() { //deprecated
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(SINGING_KEY);
        return converter;
    }

    @Bean
    public TokenStore tokenStore() { //deprecated
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    @Primary
    public DefaultTokenServices tokenServices() { //deprecated
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }
}

资源服务器配置

@Configuration
@EnableResourceServer //deprecated
public class ResourceServerOAuth2Config extends ResourceServerConfigurerAdapter { //deprecated
}

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>com.skill.improvement</groupId>
        <artifactId>app</artifactId>
        <version>1.0.1-SNAPSHOT</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>

    <artifactId>security</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <!-- 2.3.1.RELEASE -->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!-- 2.3.1.RELEASE -->
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            <version>2.3.1.RELEASE</version>
        </dependency>
    </dependencies>
</project>

主安全配置

@Order(1)
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String ADMIN_PASSWORD = "";
    private static final String USER_PASSWORD = "";

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .httpBasic().disable()
                .csrf().disable()
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers("/v1/**").authenticated()
                .and().exceptionHandling().authenticationEntryPoint(new JwtAuthenticationEntryPoint())
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler()) //deprecated
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
                .antMatchers(
                "/v2/api-docs",
                "/configuration/ui",
                "/swagger-resources/**",
                "/configuration/security",
                "/swagger-ui.html",
                "/webjars/**")
        .antMatchers(HttpMethod.GET, "/v1/**")
        .antMatchers(HttpMethod.PATCH, "/v1/**");
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(inMemoryUserDetailsManager());
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public InMemoryUserDetailsManager inMemoryUserDetailsManager() {

        return new InMemoryUserDetailsManager(getDefaultUsers());
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public OncePerRequestFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter();
    }

    private List<UserDetails> getDefaultUsers() {

        List<UserDetails> userDetailsList = new ArrayList<>();
        userDetailsList.add(User.withUsername("admin").password(passwordEncoder().encode(ADMIN_PASSWORD))
                .roles("ADMIN").build());
        userDetailsList.add(User.withUsername("user").password(passwordEncoder().encode(USER_PASSWORD))
                .roles("USER").build());
        return userDetailsList;
    }
}

一切都运行得很好,但是自从Spring Security 5.2.x以来,几乎所有的东西都被弃用了。我读了this guide

但我不确定如何成功完成迁移。有什么通俗易懂的指南教你怎么做吗?

cuxqih21

cuxqih211#

在Spring Security的当前版本中,他们还没有给出对授权服务器的支持。他们正在致力于授权服务器支持,但该项目处于实验模式。此外,Spring安全团队已经在Spring Security 5中集成了资源服务器以及OAuth2客户端支持,作为单一的Spring安全项目。在他们不发布对最新的Spring授权服务器的支持之前,您可以使用旧的授权服务器,但您将无法保留您的资源服务器身份验证服务器,因为最新的资源服务器和客户端配置具有不同的依赖关系,并且配置将与旧的OAuth2支持冲突。

我建议您在他们发布Spring最新的身份验证服务器时使用任何其他授权服务器。我建议您使用我个人使用的KeyClock身份验证服务器。

this

相关问题