Add Dependencies
Include the necessary dependencies in your pom.xml (for Maven):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
</dependency>
Configure Active Directory Connection in application.properties
spring.ldap.urls=ldap://your-ad-server:389
spring.ldap.base=dc=yourdomain,dc=com
spring.ldap.username=admin@yourdomain.com
spring.ldap.password=yourpassword
Implement LDAP Authentication in SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
)
.formLogin(withDefaults())
.httpBasic(withDefaults());
return http.build();
}
@Bean
public AuthenticationManager authManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.ldapAuthentication()
.userDnPatterns("cn={0},ou=users")
.contextSource()
.url("ldap://your-ad-server:389/dc=yourdomain,dc=com")
.and()
.passwordCompare()
.passwordEncoder(new LdapShaPasswordEncoder())
.passwordAttribute("userPassword")
.and()
.build();
}
}
Create a Login API in AuthController.java
@RestController
@RequestMapping("/auth")
public class AuthController {
@PostMapping("/login")
public ResponseEntity<String> login(@RequestBody AuthRequest authRequest) {
UsernamePasswordAuthenticationToken authToken =
new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword());
Authentication authentication = authenticationManager.authenticate(authToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
return ResponseEntity.ok("User authenticated successfully");
}
}
class AuthRequest {
private String username;
private String password;
// Getters and setters
}
Note
If your AD uses LDAPS (Secure LDAP), you may need to configure SSL certificates.
Consider JWT authentication after validating AD credentials.
Ensure role-based access control (RBAC) if needed.