How to turn on searchSubtree for LDAP on Spring boot? - spring

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;
}
}

Related

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())));
}
}
}

Spring REST security - Secure different URLs differently for different user

I am trying to provide security using spring boot security to the REST multiple endpoints with user wise but it is working for only one endpoint which depend on order and others don't work. Please suggest the solution. below my code replica
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Configuration
#Order(0)
public static class Api1WebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/getEmployees/").authenticated()
.and().httpBasic();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("bill").password("gates").roles("USER");
}
}
#Configuration
#Order(1)
public static class Api2WebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/getEmpId/).authenticated().and()
.httpBasic();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("raj").password("simran").roles("USER");
}
}

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

Spring Security does not intercept requests

I have a legacy application in which I have added Spring Web MVC libraries in order to expose a new Rest API.
I am struggling integrating spring-security in order to intercept the incoming requests. I have set up a security configuration class
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}
and a security application initializer
public class SecurityWebApplicationInitializer extends
AbstractSecurityWebApplicationInitializer {
}
following relevant guides.
Using debugger I verified that during initializing my configuration class is loaded. My problem is that my requests are not intercepted as expected.
Since you're already using Spring MVC, go to your class that initializes your application. If you're using Java Config, it most likely extends AbstractAnnotationConfigDispatcherServletInitializer.
Add your SecurityConfig to its "root config classes":
public class MySpringMmvcInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
...
#Override
protected abstract Class<?>[] getRootConfigClasses() {
return new Class[] { ..., SecurityConfig.class};
}
}
I think you forgot the #configuration annotation, try this
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
}

How to configure Spring for LDAP and JDBC?

In my web application, I have to use Spring Security and get the user's authentication details using LDAP and the user's authorization details using JDBC. The user submits a form and I get the username and password from it.
How Do I get the username and password in my WebSecurityConfig file?
How do I configure the authorization and authentication?
My WebSecurityConfig:
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().formLogin()
.loginPage("/").permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.ldapAuthentication().userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups").contextSource(contextSource());
}
#Bean
public DefaultSpringSecurityContextSource contextSource() {
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(
"ldap://mjkoldc-03.red.com");
contextSource.setUserDn("mj\\" + email);
contextSource.setPassword(password);
contextSource.setReferral("follow");
contextSource.afterPropertiesSet();
return contextSource;
}
}
Previously I was getting details using LDAPTemplate:
LdapQuery query = query().base("dc=metaljunction,dc=com")
.attributes("GivenName", "sn", "mail", "MobilePhone")
.where("ObjectClass").is("user").and("SamAccountName")
.is(email);
If you what to authentificate agains LDAP and Autorize (get user roles from JDBC) you should implement LdapAuthoritiesPopulator.
public class CustomAuthoritiesPopulator implements LdapAuthoritiesPopulator {
#Override
public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
Collection<GrantedAuthority> gas = new HashSet<GrantedAuthority>();
gas.add(new SimpleGrantedAuthority("ADMIN"));
return gas;
}
}
and add it to your SecurityConfig
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.ldapAuthoritiesPopulator(new CustomAuthoritiesPopulator())
.userSearchFilter("yourfilter")
.contextSource(contextSource());
}
}
Like this all users authentificated via LDAP will automatically get "ROLE_ADMIN".

Resources