Spring Boot security filter chain permitAll does not work as expected

I have a project in the university and I just have the problem that permitAll is not working properly in the security filter chain.
I have two filter chains, the first is for the UI with keycloak and the second is for public access for “customer” endpoints with apiKey and some should be accessible to everyone, such as for email verification.

I’ve been sitting on this problem for a few days and can’t really find a solution and I hope someone can help me.

Spring Boot version: 3.0.5
Spring Boot Security dependecies:

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>6.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
        </dependency>

My endpoints, which are validated via apiKey, work as expected, but I don’t know if it’s the best solution.

ApiFilter:

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        logger.info("ApiKeyFilter invoked for request: " + request.getRequestURI());
        if (ApiContext.isApi()) {
            String requestApiKey = request.getHeader("X-API-KEY");
            String requestApiSecret = request.getHeader("X-SECRET-KEY");

            if (requestApiKey == null || requestApiSecret == null) {
                throw new BadCredentialsException("BadCredentials");
            }

            Optional<ApiInformation> apiInformationOptional = this.apiInformationRepository.findByApiKey(requestApiKey);

            if (!apiInformationOptional.isPresent()) {
                throw new BadCredentialsException("BadCredentials");
            }

            ApiInformation apiInformation = apiInformationOptional.get();

            if (!apiInformation.getApiKey().equals(requestApiKey) || !apiInformation.getSecretKey().equals(requestApiSecret)) {
                throw new BadCredentialsException("BadCredentials");
            }

            Optional<TenantInformation> tenantInformationOptional = this.tenantInformationRepository.findByOrganization(apiInformation.getOrganization());

            if (!tenantInformationOptional.isPresent()) {
                throw new BadCredentialsException("BadCredentials");
            }

            TenantInformation tenantInformation = tenantInformationOptional.get();

            Authentication authentication = new UsernamePasswordAuthenticationToken(apiInformation.getApiKey(), null, new ArrayList<>());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            TenantContext.setCurrentTenant(tenantInformation.getTenantId());
        } else if (ApiContext.isActuator()) {
            Authentication authentication = new UsernamePasswordAuthenticationToken("GenericUser", null, new ArrayList<>());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        filterChain.doFilter(request, response);
    }

FilterChains:

    @Bean
    @Order(1)
    @DependsOn("corsConfigurationSource")
    public SecurityFilterChain apiServerFilterChain(
            HttpSecurity http,
            @Qualifier("corsConfigurationSource") CorsConfigurationSource corsConfigurationSource
    ) throws Exception {
        http.authorizeHttpRequests((authorize) ->
                        authorize.requestMatchers(
                                        GenericAbstractControllerInterface.PUBLIC_API_DOC_BASE_URI + "/**",
                                        GenericAbstractControllerInterface.API_PUBLIC_URI + "/**",
                                ).permitAll()
                                .anyRequest().authenticated()
                )
                .addFilterBefore(apiFilter, ChannelProcessingFilter.class)
                .addFilterBefore(apiKeyFilter, UsernamePasswordAuthenticationFilter.class)
                .sessionManagement(sessionManagement -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .httpBasic(withDefaults())
                .cors(cors -> {
                    cors.configurationSource(corsConfigurationSource);
                })
                .csrf(AbstractHttpConfigurer::disable);

        return http.build();
    }

    @Bean
    @Order(0)
    public SecurityFilterChain resourceServerFilterChain(
            HttpSecurity http,
            @Qualifier("corsConfigurationSource") CorsConfigurationSource corsConfigurationSource
    ) throws Exception {
        List<Subscription> subscriptions = subscriptionRepository.findAll();
        List<String> allRoles = subscriptions.stream()
                .map(subscription -> subscription.getRoles().split(",")) 
                .flatMap(Arrays::stream) 
                .collect(Collectors.toList());
        allRoles.add("ORGANIZATION_ADMIN");
        allRoles.add("ORGANIZATION_USER");

        http.authorizeHttpRequests(
                authorizeRequests -> {
                    try {
                        authorizeRequests.requestMatchers(
                                GenericAbstractControllerInterface.API_PUBLIC_URI + "/**"
                        ).permitAll()
                                .anyRequest().authenticated().and().oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwtAuthConverter);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }

                }
        );
        http.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()).disable());
        http.sessionManagement(sessionManagement -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        http.httpBasic(withDefaults());
        http.cors(cors -> cors.configurationSource(corsConfigurationSource));

        return http.build();
    }


    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);
        configuration.addAllowedOriginPattern("*");
        configuration.setAllowedMethods(Arrays.asList(
                HttpMethod.GET.name(),
                HttpMethod.POST.name(),
                HttpMethod.PUT.name(),
                HttpMethod.DELETE.name(),
                HttpMethod.OPTIONS.name()
        ));
        configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization", "Access-Control-Allow-Methods", "X-TENANT-ID", "X-API-KEY", "X-ACTUATOR", "X-GUI"));

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

The ApiFilter just checks where the request comes from and sets a global variable to validate and check other processes.
It sets e.g. if the request goes to the public Api to PUBLIC_API, GUI or API

My endpoints, which are validated via apiKey, work as expected, but I don’t know if it’s the best solution.

ApiFilter:

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        logger.info("ApiKeyFilter invoked for request: " + request.getRequestURI());
        if (ApiContext.isApi()) {
            String requestApiKey = request.getHeader("X-API-KEY");
            String requestApiSecret = request.getHeader("X-SECRET-KEY");

            if (requestApiKey == null || requestApiSecret == null) {
                throw new BadCredentialsException("BadCredentials");
            }

            Optional<ApiInformation> apiInformationOptional = this.apiInformationRepository.findByApiKey(requestApiKey);

            if (!apiInformationOptional.isPresent()) {
                throw new BadCredentialsException("BadCredentials");
            }

            ApiInformation apiInformation = apiInformationOptional.get();

            if (!apiInformation.getApiKey().equals(requestApiKey) || !apiInformation.getSecretKey().equals(requestApiSecret)) {
                throw new BadCredentialsException("BadCredentials");
            }

            Optional<TenantInformation> tenantInformationOptional = this.tenantInformationRepository.findByOrganization(apiInformation.getOrganization());

            if (!tenantInformationOptional.isPresent()) {
                throw new BadCredentialsException("BadCredentials");
            }

            TenantInformation tenantInformation = tenantInformationOptional.get();

            Authentication authentication = new UsernamePasswordAuthenticationToken(apiInformation.getApiKey(), null, new ArrayList<>());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            TenantContext.setCurrentTenant(tenantInformation.getTenantId());
        } else if (ApiContext.isActuator()) {
            Authentication authentication = new UsernamePasswordAuthenticationToken("GenericUser", null, new ArrayList<>());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        filterChain.doFilter(request, response);
    }

FilterChains:

    @Bean
    @Order(1)
    @DependsOn("corsConfigurationSource")
    public SecurityFilterChain apiServerFilterChain(
            HttpSecurity http,
            @Qualifier("corsConfigurationSource") CorsConfigurationSource corsConfigurationSource
    ) throws Exception {
        http.authorizeHttpRequests((authorize) ->
                        authorize.requestMatchers(
                                        GenericAbstractControllerInterface.PUBLIC_API_DOC_BASE_URI + "/**",
                                        GenericAbstractControllerInterface.API_PUBLIC_URI + "/**",
                                ).permitAll()
                                .anyRequest().authenticated()
                )
                .addFilterBefore(apiFilter, ChannelProcessingFilter.class)
                .addFilterBefore(apiKeyFilter, UsernamePasswordAuthenticationFilter.class)
                .sessionManagement(sessionManagement -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .httpBasic(withDefaults())
                .cors(cors -> {
                    cors.configurationSource(corsConfigurationSource);
                })
                .csrf(AbstractHttpConfigurer::disable);

        return http.build();
    }

    @Bean
    @Order(0)
    public SecurityFilterChain resourceServerFilterChain(
            HttpSecurity http,
            @Qualifier("corsConfigurationSource") CorsConfigurationSource corsConfigurationSource
    ) throws Exception {
        List<Subscription> subscriptions = subscriptionRepository.findAll();
        List<String> allRoles = subscriptions.stream()
                .map(subscription -> subscription.getRoles().split(",")) 
                .flatMap(Arrays::stream) 
                .collect(Collectors.toList());
        allRoles.add("ORGANIZATION_ADMIN");
        allRoles.add("ORGANIZATION_USER");

        http.authorizeHttpRequests(
                authorizeRequests -> {
                    try {
                        authorizeRequests.requestMatchers(
                                GenericAbstractControllerInterface.API_PUBLIC_URI + "/**"
                        ).permitAll()
                                .anyRequest().authenticated().and().oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwtAuthConverter);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }

                }
        );
        http.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler()).disable());
        http.sessionManagement(sessionManagement -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        http.httpBasic(withDefaults());
        http.cors(cors -> cors.configurationSource(corsConfigurationSource));

        return http.build();
    }


    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);
        configuration.addAllowedOriginPattern("*");
        configuration.setAllowedMethods(Arrays.asList(
                HttpMethod.GET.name(),
                HttpMethod.POST.name(),
                HttpMethod.PUT.name(),
                HttpMethod.DELETE.name(),
                HttpMethod.OPTIONS.name()
        ));
        configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization", "Access-Control-Allow-Methods", "X-TENANT-ID", "X-API-KEY", "X-ACTUATOR", "X-GUI"));

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

The ApiFilter just checks where the request comes from and sets a global variable to validate and check other processes.
It sets e.g. if the request goes to the public Api to PUBLIC_API, GUI or API

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật