在最新版本的Spring Boot中,类已被弃用,您必须使用新样式来编写安全配置,2.7.2
WebSecurityConfigurerAdapter
Spring Security without the WebSecurityConfigurerAdapter
话虽如此,下面这样的东西适用于Spring Boot 2.7.2。我有一个 JWT 令牌筛选器,需要插入该筛选器来验证传入的 JWT 令牌。试图突出用法 -SecurityFilterChain
& AuthenticationConfiguration
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.util.matcher.RequestMatcher;
//import my custom jwt class package;
import lombok.RequiredArgsConstructor;
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class WebSecurityConfig {
private final AuthenticationConfiguration authConfiguration;
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return authConfiguration.getAuthenticationManager();
}
@Autowired
public void configure(AuthenticationManagerBuilder builder, AuthenticationProvider jwtAuthenticationProvider) {
builder.authenticationProvider(jwtAuthenticationProvider);
}
@Bean
public SecurityFilterChain configure(HttpSecurity http, AuthenticationEntryPoint authenticationEntryPoint,
RequestMatcher requestMatcher)
throws Exception {
http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.GET, List.of("/favicon.ico", "/**/*.html").toArray(new String[0])).permitAll();
AbstractAuthenticationProcessingFilter jwtFilter = new MyCustomClass(requestMatcher);
jwtFilter.setAuthenticationManager(authenticationManager());
http.addFilterBefore(jwtFilter, BasicAuthenticationFilter.class);
return http.build();
}
}