Spring安全迁移指南5



我有多模块maven项目Spring boot 2.3.1.RELEASE,在那里我使用OAuth 2.0上的Spring安全性。我的一个模块包含安全配置:

授权服务器配置

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

一切都很好,但自从SpringSecurity5.2.x以来,几乎所有的东西都被弃用了

但我不确定如何成功完成迁移。关于如何做,有什么可以理解的指南吗?

在springsecurity的当前版本中,他们没有提供授权服务器的支持。他们正在研究授权服务器支持,但该项目处于实验模式。此外,springsecurity团队已经将springsecurity5中的资源服务器和Oauth2客户端支持集成为单个springsecurities项目。在他们没有发布对最新spring授权服务器的支持之前,您可以使用旧的授权服务器,但无法保留资源服务器auth服务器,因为最新的资源服务器和客户端配置具有不同的依赖关系,并且配置将与旧的oauth2支持相冲突。

我建议您在发布spring最新的auth服务器的同时使用任何其他授权服务器。我建议您使用我个人使用的keyclockauth服务器。

查看此

对于所有想要使用最新解决方案的人,Spring已经发布了授权服务器。

Maven依赖项:

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-authorization-server</artifactId>
<version>1.0.0</version>
</dependency>

最新更新