简体   繁体   English

Spring 引导 3 多个安全过滤器链不起作用

[英]Spring boot 3 multiple security filter chains doesn't work

I am using Spring Boot 3.0.1.我正在使用 Spring Boot 3.0.1。 In my WebSecurityConfig class, I want to filter 2 types of api urls.在我的 WebSecurityConfig class 中,我想过滤 2 种类型的 api url。 So I have 2 SecurityFilterChains.所以我有 2 个 SecurityFilterChain。 This is what I want to achieve.这就是我想要实现的。

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

The following code has only 1 SecurityFilterChain and it works perfectly fine to satisfy all the above 1,2,3 points.下面的代码只有 1 个 SecurityFilterChain,它可以完美地满足上述所有 1、2、3 点。 For 1, it will create the session id in the spring_session table with the login user as the principal_name.对于 1,它会在 spring_session 表中创建 session id,登录用户作为 principal_name。 For 2, it will also create another session id in spring_session table with "client" as the principal_name.对于 2,它还会在 spring_session 表中创建另一个 session id,并将“client”作为 principal_name。 I do not want to create a session id for 2. I only want to create session id when I call the 1 (login api).我不想为 2 创建 session id。我只想在调用 1(登录 api)时创建 session id。 So I believe that I have to write 2 Filter chains.所以我认为我必须编写 2 个过滤器链。 First one only for login api and create session id, second one for all the white apis to go through with out security/session checks.第一个仅用于登录 api 并创建 session id,第二个用于所有白色 api 到 go,通过安全/会话检查。 How do I write 2 security filter chains?如何编写 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();
    }
}

Create more SecurityFilterChain Bean and add @Order(1) and @Order(2) annotations.创建更多 SecurityFilterChain Bean 并添加 @Order(1) 和 @Order(2) 注释。

Check the Spring docs: https://docs.spring.io/spring-security/reference/servlet/architecture.html#servlet-securityfilterchain检查 Spring 文档: https://docs.spring.io/spring-security/reference/servlet/architecture.html#servlet-securityfilterchain

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring 引导 - 来自依赖项的多个过滤器链 - Spring Boot - Multiple filter chains from dependencies 使用Spring Security保护Spring Boot Web App无效 - Securing Spring Boot Web App With Spring Security Doesn't Work UsernameNotFoundException:Spring Boot + Spring Security中的登录表单不起作用 - UsernameNotFoundException: Login form in Spring Boot + Spring Security doesn't work CSS 样式表不适用于 Spring Security + Spring Boot + Thymeleaf - CSS stylesheet doesn't work with Spring Security + Spring Boot + Thymeleaf 注销不适用于 Spring Boot、Spring Security 和 Thymleaf - Logout doesn't work with Spring Boot, Spring Security and Thymleaf Thymeleaf 安全性无法正常工作(Spring Boot) - Thymeleaf security doesn't work properly (Spring Boot) Spring Boot Security-蚂蚁匹配器不起作用 - Spring Boot Security - Ant Matcher doesn't work 没有Spring Boot的Spring Security身份验证与Spring Boot和类似配置不兼容 - Spring security authentication without spring boot doesn't work as opposed to with spring boot and similar configuration Spring 引导 @DataJpaTest 排除过滤器不起作用 - Spring boot @DataJpaTest exclude filter doesn't work Spring Boot Actuator Endpoints 安全性不适用于自定义 Spring 安全配置 - Spring Boot Actuator Endpoints security doesn't work with custom Spring Security Configuration
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM