java Spring Security 6安全过滤器链优先级Web安全定制器

mpgws1up  于 2023-02-20  发布在  Java
关注(0)|答案(1)|浏览(326)

在Spring Security 6中,我对securityFilterChain进行了如下配置:

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

    http.csrf()
        .disable()
        .cors()
        .and()
        .exceptionHandling()
        .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeHttpRequests(
                authorize -> authorize
                    .requestMatchers(HttpMethod.OPTIONS).permitAll()
                    .requestMatchers(HttpMethod.GET,"/articles/feed").authenticated()
                    .requestMatchers(HttpMethod.POST, "/users",  "/users/login").permitAll()
                    .requestMatchers(HttpMethod.GET, "/articles/**", "/profiles/**", "/tags").permitAll()
                    .anyRequest().authenticated()
                    )
        .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
  }

为了启用h2-console,我添加了以下内容:

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

但是我发现SecurityFilterChain中的配置优先于我在WebSecurityCustomizer中设置的配置。例如,jwtRequestFilter仍然为/h2-console/** url提供午餐
我可以在过滤器链中配置/h2-console/*,但我想知道是否有其他方法。

fnvucqvd

fnvucqvd1#

问题出在webSecurityCustomizer
requestMatchers应设置为AntPathRequestMatcher,而不是默认值MvcRequestMatcher

@Bean
WebSecurityCustomizer webSecurityCustomizer() {
    return web -> web.ignoring().requestMatchers(
                       new AntPathRequestMatcher("/h2-console/**")
                    );
}

相关问题