Spring Security从Sping Boot 2.6.6升级到Sping Boot 3.1.2

8gsdolmq  于 2023-10-20  发布在  Spring
关注(0)|答案(3)|浏览(175)

我正在将Sping Boot 应用程序从Sping Boot 2.6.6迁移到3.1.2,其中http安全性中的大多数方法都被弃用或删除。
我在谷歌上搜索了很多地方,但我无法将此特定配置转换为Sping Boot 3. 1. X配置。
下面是使用扩展WebSecurityConfigurerAdapter的类编写的方法。注意:preAuthFilter()、accessDeniedFilter()和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*"));
    }

这段代码似乎不起作用,因为我在调用方法时在控制器和过滤器中得到null:SecurityContextHolder.getContext().getAuthentication(),即使在一个API中使用URL“rest/dologin/{userId}”设置它之后也是如此
以前用旧的配置它是工作,但现在不是,可以有人请尝试帮助我在改变这个配置?

rqqzpn5f

rqqzpn5f1#

我在Spring Boot 3做了安全配置,也许能帮到你

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    private final JwtFilter jwtFilter;
    private final JwtAuthenticationEntryPoint authenticationEntryPoint;
    private final JWTAccessDeniedHandler accessDeniedHandler;

    public SecurityConfig(JwtFilter jwtFilter, JwtAuthenticationEntryPoint authenticationEntryPoint, JWTAccessDeniedHandler accessDeniedHandler) {
        this.jwtFilter = jwtFilter;
        this.authenticationEntryPoint = authenticationEntryPoint;
        this.accessDeniedHandler = accessDeniedHandler;
    }

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

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .headers().frameOptions().disable().and()
                .csrf().disable()
                .cors().and()
                .authorizeHttpRequests(auth -> {
                    auth.requestMatchers("/api/public", "/h2-console/**", "/api/auth/login", "/api/auth/signup", "/**").permitAll();
                    auth.requestMatchers("/api/v1/admin").hasAuthority("ADMIN");
                    auth.requestMatchers("/api/v1/area").hasAnyAuthority("ADMIN", "USER");
                    auth.anyRequest().authenticated();
                })
                .formLogin().disable()
                .httpBasic().disable()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler)
                .authenticationEntryPoint(authenticationEntryPoint)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().requestMatchers
                ("/api/public", "/h2-console/**", "/api/auth/login", "/api/auth/signup", "/**");
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedMethods("*");
            }
        };
    }
}
vdgimpew

vdgimpew2#

Spring Security更新了。WebSecurityConfigurerAdapter不再支持。你可以检查here。这可以帮助你:

import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;    
import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

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

        AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
        http.addFilter(new CustomFilter(authenticationManager));

        http.authorizeHttpRequests((authz) -> authz
                        .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
                        .requestMatchers("/rest/saveTodo*").hasRole("ADMIN")
                        .requestMatchers("/**").denyAll()
                        .requestMatchers(
                                "/**/index*",
                                "/**/logout/",
                                "/**/logoutApp",
                                "/rest/getversion*",
                                "/rest/dologin/*",
                                "/rest/menu*",
                                "/rest/getScript*",
                                "/rest/**").permitAll()
                        .anyRequest().permitAll())
                .formLogin(withDefaults()).exceptionHandling((exceptionHandling) ->
                        exceptionHandling.authenticationEntryPoint(forbiddenEntryPoint()))
                .exceptionHandling((exceptionHandling) ->
                        exceptionHandling.accessDeniedHandler(accessDeniedHandler())) // Use the AccessDeniedHandler bean here
                .and()             
                .csrf().disable()
                .headers().disable();     

}
wi3ka0sx

wi3ka0sx3#

根据您的信息,在迁移到3.1.2版本之前,所有工作都很好,SecurityContextHolder.getContext().getAuthentication()没有返回null。问题出在最新的配置中。
同样根据2.6.6的最旧配置,3.1.2配置应该是这样的:

@Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
      http.csrf(AbstractHttpConfigurer::disable);
      http.headers(AbstractHttpConfigurer::disable);
      http.exceptionHandling(handlingConfigurer -> {
              handlingConfigurer.accessDeniedPage(accessDeniedHandler());
              handlingConfigurer.authenticationEntryPoint(forbiddenEntryPoint());
      });
      http.addFilterAt(preAuthFilter(), AbstractPreAuthenticatedProcessingFilter.class);
      http.authorizeHttpRequests(request -> {
         request.requestMatchers("/**/index*",
             "/**/logout/",
             "/**/logoutApp",
             "/rest/getversion*",
             "/rest/dologin/*",
             "/rest/menu*",
             "/rest/getScript*",
             "/rest/**").permitAll();
         request.requestMatchers("/rest/saveTodo*").hasRole("ADMIN");
         request.requestMatchers("/**").denyAll();
          });
      return http.build();
    }

  @Bean
  public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring().requestMatchers("/**/*.png*","/**/*.js*","/**/*.jpg*","/**/*.svg*","/**/*.ico*",
            "/**/*.css*","/**/login*","/**/*.woff*","/**/*.ttf*","/**/*.eot*");
  }

相关问题