Integration with Active Directory using spring boot ldap - spring

i am new to concept of active directory, so to integrate active directory with ldap i am using spring boot framework i.e using spring security with ldap.
So based on same reference from stackoverflow i am not able to managed authentication with active directory.
Below is my sample code :
#Configuration
#EnableGlobalAuthentication
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().fullyAuthenticated().and().formLogin();
}
#Bean
public ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
ActiveDirectoryLdapAuthenticationProvider activeDirectoryLdapAuthenticationProvider = new ActiveDirectoryLdapAuthenticationProvider(
"xyzabcd.org", "ldap://192.168.100.161:389/");
return activeDirectoryLdapAuthenticationProvider;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication().userDnPatterns("uid={0},ou=Users").contextSource(contextSource());
}
#Bean
public DefaultSpringSecurityContextSource contextSource() {
return new DefaultSpringSecurityContextSource(Arrays.asList("ldap://192.168.100.161:389/"),
"DC=xyzabcd.org,DC=org");
}
}
with this i am getting below error
Your login attempt was not successful, try again.
Reason: Bad credentials
so guys please help me out with this problem
Thanks

Related

Spring Security Active Directory Authentication - infinite login pop-up

I am using Spring Boot (2.7.2) security. My security config is:
public class WebSecurityConfig {
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().fullyAuthenticated().and().httpBasic();
return http.build();
}
#Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(
"company.com", "ldap://ldap-company.com:389");
provider.setSearchFilter("(&(objectClass=user)(sAMAccountName={0}))");
provider.setConvertSubErrorCodesToExceptions(true);
provider.setUseAuthenticationRequestCredentials(true);
return provider;
}
}
Now when I hit my URI I keep getting the login pop-up infinitely.
The username and password I am providing is correct. No error(s) at the console whatsoever.
What am I doing wrong here or missing?
While I am still waiting for the right answer, I got the idea from here and it works.
So this is what I ended up with:
public class WebSecurityConfig extends GlobalAuthenticationConfigurerAdapter {
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
// .fullyAuthenticated()
.and().httpBasic();
return http.build();
}
#Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(
"ldap://ldap-company.com:389/dc=company,dc=com");
contextSource.setUserDn("CN=MYBindUser,OU=Ldap,dc=COMPANY,dc=com");
contextSource.setPassword("ComplexP#ssw0rd");
contextSource.setReferral("follow");
contextSource.afterPropertiesSet();
LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> ldapAuthenticationProviderConfigurer = auth
.ldapAuthentication();
ldapAuthenticationProviderConfigurer
.userSearchFilter("(&(cn={0}))")
// .userSearchFilter("(sAMAccountName=%s)")
.userSearchBase("")
// .groupSearchBase("(&(objectCategory=group)(cn={0}))")
.contextSource(contextSource);
}
}
Now my HTTPBasic Authentication with ActiveDirectory LDAP works just fine.

Authentication provider per url pattern - Spring Boot

I faced problem when configuring different auth providers per url pattern using Spring Boot security. I am trying to configure security in Spring Boot app and want to have swagger behind basic auth and all API is secured only by token. I have it almost working, but noticed that API except the fact that it is secured by token which is verified by IDAuthProvider class it also is secured by basic auth. I do not want that and also noticed that if I removed line:
sessionCreationPolicy(SessionCreationPolicy.STATELESS).
it seems to be working correctly, but still header Basic {token} is being added in request which is something I do not want...
Do you know how can I configure it to make all swagger stuff secured by basic auth and API stuff secured by token?
My configuration looks like below:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Configuration
#Order(1)
public class SwaggerSecurityConfig extends WebSecurityConfigurerAdapter {
private final AuthenticationProvider userPassAuthProvider;
#Autowired
SwaggerSecurityConfig(UserPassAuthProvider userPassAuthProvider) {
this.userPassAuthProvider = userPassAuthProvider;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/swagger**").
authorizeRequests().
antMatchers("/swagger**").authenticated().
and().httpBasic().and().csrf().disable();
}
#Override
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(userPassAuthProvider);
}
}
#Configuration
#Order(2)
public class APISecurityConfig extends WebSecurityConfigurerAdapter {
private final AuthenticationProvider idAuthProvider;
#Autowired
APISecurityConfig(IDAuthProvider idAuthProvider) {
this.idAuthProvider = idAuthProvider;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/api/v1/**").
authorizeRequests().anyRequest().authenticated().
and().
addFilterBefore(idpAuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class).sessionManagement().
and().
csrf().disable();
}
#Override
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(idAuthProvider);
}
IDPAuthenticationFilter idpAuthenticationFilter(AuthenticationManager auth) {
return new IDPAuthenticationFilter(auth, new OrRequestMatcher(new AntPathRequestMatcher(ApiRouter.API_PATH + "/**", HttpMethod.GET.toString()), new AntPathRequestMatcher(ApiRouter.API_PATH + "/**", HttpMethod.POST.toString()), new AntPathRequestMatcher(ApiRouter.API_PATH + "/**", HttpMethod.DELETE.toString()), new AntPathRequestMatcher("/swagger**", HttpMethod.GET.toString())));
}
}
}

Multiple authentication provider for specific url - Spring Boot Security

In Spring security I want to use Basic authentication for urls starting with api/** LDAP Rest Authentication for urls starting with /ldap/. The current code i have also allows ldap/ with basic authentication.
The question comes even if i use them as separate AuthenticationProviders like LdapAuthProvider and BasicAuthProvider how can i use it to point to the specific urls
#Configuration
#EnableWebSecurity
public class WebSecurityConfig {
#Configuration
#Order(1)
public class BasicAuthenticationProvider extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/swagger-ui*", "/info", "/health").permitAll()
.and().authorizeRequests().antMatchers("/order/**").fullyAuthenticated()
.and().httpBasic().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().csrf().disable()
.anonymous().disable();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(inMemoryUserDetailsManager());
}
}
#Configuration
#Order(2)
public class LdapAuthenticationProvider extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/ldap/**").fullyAuthenticated().and().httpBasic()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.ldapAuthentication() code here......
}
}
}
As far as I understand, You have multiple entry points in one application and there are different types of users that can access different portions of the application.
You should look at this Baeldung tutorial: Multiple Entry Points in Spring Security

How to turn on searchSubtree for LDAP on Spring boot?

I have a Spring boot application with LDAP authentication.
I need to have javax.naming.directory.SearchControls with SUBTREE_SCOPE to be able to retrieve the user groups, but I can't find a way to turn that on.
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication()
.userSearchFilter(ldap.getUserFilter())
.userSearchBase(ldap.getUserBaseDN())
.groupSearchFilter(ldap.getGroupFilter())
.groupSearchBase(ldap.getGroupBaseDN())
.groupRoleAttribute(ldap.getGroupNameAttribute())
.contextSource()
.url(ldap.getUrl())
.managerDn(ldap.getManagerDn())
.managerPassword(ldap.getManagerPassword());
}
public void setLdap(LdapProperties ldap) {
this.ldap = ldap;
}
}

Spring Boot LDAP Authentication: Always get bad credentials

I'm trying to authenticate with a Spring Boot application against an Active Directory server in my local network, but I don't know what could I be doing wrong.
When I access localhost I am redirected to the login page:
Whenever I write any real user credentials, I'm redirected to the same page with an error message:
If I send a random word as user and password I get the same login error screen, but additionaly this message is shown from Eclipse console:
2016-02-04 18:54:47.591 INFO 10092 --- [nio-8080-exec-8] ctiveDirectoryLdapAuthenticationProvider : Active Directory authentication failed: Supplied password was invalid
From the Active Directory Server, the distinguishedName of the group that I want to access is: CN=Bulnes,OU=Usuarios Locales,DC=Bulnes,DC=local, so it is configured in security configuration class like this:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**").permitAll()
.anyRequest().fullyAuthenticated()
.and()
.formLogin();
}
#Configuration
protected static class AuthenticationConfiguration extends
GlobalAuthenticationConfigurerAdapter {
#Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
ActiveDirectoryLdapAuthenticationProvider provider=
new ActiveDirectoryLdapAuthenticationProvider("bulnes.local"
,"ldap://192.168.1.3:389/"
,"CN=Bulnes,OU=Usuarios Locales,DC=Bulnes,DC=local");
auth.authenticationProvider(provider);
}
}
}
This is how I have it working:
ad.properties
ad.url=ldap://yourserver.abc.com:389
ad.domain=abc.com
WebSecurityConfig.java
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Value("${ad.domain}")
private String adDomain;
#Value("${ad.url}")
private String adUrl;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login", "/css/**", "/public/**").permitAll().anyRequest().authenticated()
.and().formLogin().loginPage("/login").defaultSuccessUrl("/", true)
.failureUrl("/login?failed=badcredentials")
.permitAll().and().logout().logoutUrl("/logout")
.logoutSuccessUrl("/login");
}
#Bean
#Override
public AuthenticationManager authenticationManager() {
return new ProviderManager(Arrays.asList(activeDirectoryLdapAuthenticationProvider()));
}
#Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(adDomain,
adUrl);
provider.setConvertSubErrorCodesToExceptions(true);
provider.setUseAuthenticationRequestCredentials(true);
return provider;
}
}
Just created the provider like this, and it works fine.
ActiveDirectoryLdapAuthenticationProvider provider=
new ActiveDirectoryLdapAuthenticationProvider("bulnes.local"
,"ldap://192.168.1.3:389);
It still gives an exception but at least authenticates
2016-02-04 21:30:36.293 INFO 12056 --- [nio-8080-exec-3] o.s.s.ldap.SpringSecurityLdapTemplate : Ignoring PartialResultException

Resources