Spring Boot 3多重安全过滤器链不工作

b4lqfgs4  于 2023-01-09  发布在  Spring
关注(0)|答案(1)|浏览(198)

我使用的是Sping Boot 3.0.1,在我的WebSecurityConfig类中,我想过滤2种类型的API url,所以我有2个SecurityFilterChains,这就是我想要实现的。

1.) Login api: This one, I want to permit this url and save the session id to the database using Spring Sessions.
2.) Other white apis: I want to permit some urls without any security/session checks
3.) Any other api calls need to have the x-auth-token

下面的代码只有一个SecurityFilterChain,它可以完美地满足上面的1、2、3点:对于1,它将在spring_session表中创建会话ID,并将登录用户作为principal_name;对于2,它还将在spring_session表中创建另一个会话id,其中“client”作为principal_name。我不想为2创建会话id。我只想在调用1(登录API)时创建会话ID。所以我认为我必须编写2个过滤器链。第一个只用于登录API和创建会话ID,第二个用于所有白色API,不进行安全/会话检查。我如何编写2个安全过滤器链?

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig {

    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http)
            throws Exception {
        var daoAC = new DaoAuthenticationConfigurer(userDetailsService);
        daoAC.passwordEncoder(passwordEncoder);
        var builder = http.getSharedObject(AuthenticationManagerBuilder.class);
        builder.apply(daoAC);
        return builder.build();
    }

    private static final String[] AUTH_WHITELIST = {           
            "/api/usermanager/auth/login",
            "/api/usermanager/auth/app-login",
            "/api/usermanager/auth/resetPassword",
            "/api/usermanager/auth/health",
            "/api/usermanager/back-office/login",
            "/actuator/**",
            "/get-user-names",
            "/get-users",
            "/get-user",
            "/api/usermanager/users/activate",
            "/actuator/**",
            "/health/**",
            "/api/usermanager/org",
            "/api/usermanager/org/*/theme",
            "/api/usermanager/image/org/*/all",
            "/api/usermanager/image/org/*/logo.png"
    };

    @Bean   
    public SecurityFilterChain loginFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf().disable().exceptionHandling()
                .authenticationEntryPoint(restAuthenticationEntryPoint)
                .and().securityContext((securityContext) -> securityContext.requireExplicitSave(false))
                .cors()
                .and()
                .httpBasic()
                .and()
                .securityMatcher("/api/**")
                .authorizeHttpRequests(
                        requests -> requests.
                                requestMatchers(AUTH_WHITELIST).permitAll()
                                .anyRequest().authenticated()
                ).httpBasic(withDefaults())
                .sessionManagement(session ->  session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                        .sessionFixation()
                        .migrateSession()
                        .maximumSessions(1)
                        .expiredUrl("/sessionExpired.html")
                        .maxSessionsPreventsLogin(false));
        return http.build();
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().requestMatchers(HttpMethod.GET,
                "/docs/**", "/resources/**", "/static/**", "/img/**");
    }

    @Bean
    public AuthenticationFailureHandler myFailureHandler() {
        return new CustomAuthenticationFailureHandler();
    }

    @Bean
    public HttpSessionIdResolver httpSessionStrategy() {
        return HeaderHttpSessionIdResolver.xAuthToken();
    }

    @Bean
    public HttpSessionIdResolver httpSessionIdResolver() {
        return HeaderHttpSessionIdResolver.xAuthToken();
    }

    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }
}
6fe3ivhb

6fe3ivhb1#

创建更多的SecurityFilterChainBean并添加@Order(1)和@Order(2)注解。
检查Spring文档:https://docs.spring.io/spring-security/reference/servlet/architecture.html#servlet-securityfilterchain

相关问题