Infinite loop in Spring Boot when entering incorrect credentials for Active Directory authentication

I’m working on a Spring Boot application with Spring Security and Active Directory for authentication and I’ve set up a virtual machine with Windows Server 2019 to connect to my Active Directory. The authentication works find when I enter valid credentials, however, when I enter incorrect credentials I encounter an infinite loop of errors, so here’s my WebSecurityConfig:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    private static final String DOMAIN = "xxxxxx.net";
    private static final String URL = "ldap://xxxxxxxx:389/";

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf(AbstractHttpConfigurer::disable)
                .cors(cors -> cors
                        .configurationSource(request -> {
                            CorsConfiguration corsConfiguration = new CorsConfiguration();
                            corsConfiguration.setAllowedOrigins(List.of("http://localhost:4200"));
                            corsConfiguration.setAllowedMethods(List.of("POST", "PUT", "GET", "DELETE", "OPTIONS"));
                            corsConfiguration.setAllowedHeaders(List.of("Authorization", "Content-Type"));
                            corsConfiguration.setAllowCredentials(true);
                            return corsConfiguration;
                        }))
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("auth/**").permitAll()
                        .anyRequest().authenticated())
                .formLogin(login -> login.permitAll())
        .sessionManagement(session ->
                        session.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED));
        return http.build();
    }



    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
        AuthenticationManagerBuilder auth = http.getSharedObject(AuthenticationManagerBuilder.class);

        ActiveDirectoryLdapAuthenticationProvider adProvider =
                new ActiveDirectoryLdapAuthenticationProvider(DOMAIN, URL);
        adProvider.setConvertSubErrorCodesToExceptions(true);
        adProvider.setUseAuthenticationRequestCredentials(true);

        auth.authenticationProvider(adProvider);

        return auth.build();
    }
}

Here’s my controller

@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Login login, HttpServletRequest request, HttpServletResponse response) {
        try {
            UsernamePasswordAuthenticationToken authToken =
                    new UsernamePasswordAuthenticationToken(login.getUser(), login.getPassword());
            authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            Authentication auth = authenticationManager.authenticate(authToken);

            SecurityContextHolder.getContext().setAuthentication(auth);

            HttpSession session = request.getSession(true);
            session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());

            return ResponseEntity.ok().body("{"message": "Login Successful"}");
        } catch (AuthenticationException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("{"error": "Login Failed: " + e.getMessage() + ""}");
        }
    }

}

This is the error

2024-06-21T14:55:11.425-05:00 DEBUG 21880 --- [waza] [nio-8080-exec-4] o.s.security.web.FilterChainProxy        : Securing OPTIONS /auth/login
2024-06-21T14:55:11.428-05:00 DEBUG 21880 --- [waza] [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : Securing POST /auth/login
2024-06-21T14:55:11.428-05:00 DEBUG 21880 --- [waza] [nio-8080-exec-9] o.s.s.w.session.SessionManagementFilter  : Request requested invalid session id 3483544F478CB1A816B1EE2D674EC902
2024-06-21T14:55:11.429-05:00 DEBUG 21880 --- [waza] [nio-8080-exec-9] o.s.security.web.FilterChainProxy        : Secured POST /auth/login
2024-06-21T14:55:11.432-05:00 DEBUG 21880 --- [waza] [nio-8080-exec-9] ctiveDirectoryLdapAuthenticationProvider : Authentication for [email protected] failed:javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C090439, comment: AcceptSecurityContext error, data 52e, v4563 ]
2024-06-21T14:55:11.432-05:00  INFO 21880 --- [waza] [nio-8080-exec-9] ctiveDirectoryLdapAuthenticationProvider : Active Directory authentication failed: Supplied password was invalid
2024-06-21T14:55:11.433-05:00 DEBUG 21880 --- [waza] [nio-8080-exec-9] ctiveDirectoryLdapAuthenticationProvider : Authentication for [email protected] failed:javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C090439, comment: AcceptSecurityContext error, data 52e, v4563 ]
2024-06-21T14:55:11.433-05:00  INFO 21880 --- [waza] [nio-8080-exec-9] ctiveDirectoryLdapAuthenticationProvider : Active Directory authentication failed: Supplied password was invalid

I know that are invalid credentials but the error appears a hundred of times, and after this, the console show me this

2024-06-21T14:55:12.908-05:00 ERROR 21880 --- [waza] [nio-8080-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed: java.lang.StackOverflowError] with root cause

java.lang.StackOverflowError: null
at java.base/java.net.URI$Parser.scanIPv4Address(URI.java:3453) ~[na:na]
at java.base/java.net.URI$Parser.parseIPv4Address(URI.java:3493) ~[na:na]
at java.base/java.net.URI$Parser.parse(URI.java:3541) ~[na:na]
at java.base/java.net.URI$Parser.parseHierarchical(URI.java:3640) ~[na:na]
at java.base/java.net.URI$Parser.parse(URI.java:3592) ~[na:na]
at java.base/java.net.URI.<init>(URI.java:600) ~[na:na]
at java.base/java.net.URI.create(URI.java:869) ~[na:na]

and a lot of info that i cant’t understand,

Finally these are my dependencies

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-ldap</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-ldap</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>13.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

Im using spring boot 3.3.0 and i’ve tried with spring boot 3.2.5 and 3.2.6 and is the same error.
I was debbuging the app and the error happens on this line
Authentication auth = authenticationManager.authenticate(authToken);
I also tried with the default login provided by spring security, but nothing works, please help, i don’t know why this happens.
Appreciate your help

New contributor

Francis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

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