我正在将一个Spring Boot应用程序从Spring Boot 2.6.6迁移到3.1.2,其中大部分http security中的方法要么已弃用,要么已删除。
我在很多地方进行了搜索,但是无法将此特定配置转换为Spring Boot 3.1.X配置。
以下是使用扩展WebSecurityConfigurerAdapter类编写的方法。 注意:preAuthFilter()、accessDeniedHandler()和forbiddenEntryPoint()是同一类中定义的方法。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/**").exceptionHandling().authenticationEntryPoint(forbiddenEntryPoint())
.and().authorizeRequests().antMatchers(
"/**/index*",
"/**/logout/",
"/**/logoutApp",
"/rest/getversion*",
"/rest/dologin/*",
"/rest/menu*",
"/rest/getScript*",
"/rest/**").permitAll().antMatchers("/rest/saveTodo*").hasRole("ADMIN")
.antMatchers("/**").denyAll()
.and()
.addFilterAt(preAuthFilter(), AbstractPreAuthenticatedProcessingFilter.class)
.exceptionHandling().accessDeniedHandler(accessDeniedHandler())
.and().csrf().disable()
.headers().disable();
}
@Override
public void configure(WebSecurity web) {
web
.ignoring()
.antMatchers("/**/*.png*","/**/*.js*","/**/*.jpg*","/**/*.svg*","/**/*.ico*",
"/**/*.css*","/**/login*","/**/*.woff*","/**/*.ttf*","/**/*.eot*");
}
我尝试将上述代码改为下面的代码:
@Bean
public SecurityFilterChain springFilterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(req -> req.requestMatchers(
new AntPathRequestMatcher(new AntPathRequestMatcher("/**"))))
.exceptionHandling(request -> request.authenticationEntryPoint(forbiddenEntryPoint()))
.authorizeHttpRequests(request -> request
.requestMatchers(
new AntPathRequestMatcher("/**/index*"),
new AntPathRequestMatcher("/**/logout/"),
new AntPathRequestMatcher("/**/logoutApp"),
new AntPathRequestMatcher("/rest/getversion*"),
new AntPathRequestMatcher("/rest/dologin/*"),
new AntPathRequestMatcher("/rest/menu*"),
new AntPathRequestMatcher("/rest/getScript*"),
new AntPathRequestMatcher("/rest/**"),
new AntPathRequestMatcher("/waveinventoryservice/**"))
.permitAll()
.requestMatchers(new AntPathRequestMatcher("/rest/saveTodo*")).hasRole("ADMIN")
.requestMatchers(new AntPathRequestMatcher("/**"))
.denyAll())
.addFilterAt(preAuthFilter(), AbstractPreAuthenticatedProcessingFilter.class)
.exceptionHandling(handler -> handler.accessDeniedHandler(accessDeniedHandler()))
.csrf(CsrfConfigurer::disable).headers(HeadersConfigurer::disable).build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().requestMatchers(new AntPathRequestMatcher("/**/*.png*"),
new AntPathRequestMatcher("/**/*.js*"),
new AntPathRequestMatcher("/**/*.jpg*"),
new AntPathRequestMatcher("/**/*.svg*"),
new AntPathRequestMatcher("/**/*.ico*"),
new AntPathRequestMatcher("/**/*.css*"),
new AntPathRequestMatcher("/**/login*"),
new AntPathRequestMatcher("/**/*.woff*"),
new AntPathRequestMatcher("/**/*.ttf*"),
new AntPathRequestMatcher("/**/*.eot*"));
}
这段代码似乎不工作,因为在调用方法
SecurityContextHolder.getContext().getAuthentication()
时,控制器和过滤器中返回了 null,即使在一个 API 中设置了 URL "rest/dologin/{userId}"。之前使用旧的配置是可以工作的,但现在不行了,请有人帮助我更改这个配置吗?