I've been given the following LDAP configuration I need to use for authentication. How does this translate into Java code?
ext ldap over SSL
ext.secure.adapter.ConnectionURL=ldap://ext_host:999
encrypted.ext.secure.adapter.UserName=CN=Administrator,CN=Users,DC=ext-pre,DC=corp-pre,DC=com
encrypted.ext.secure.adapter.Password=HelloWorld1
corp ldap over SSL
corp.secure.adapter.ConnectionURL=ldap://corp_host:888
encrypted.corp.secure.adapter.UserName=CN=Administrator,CN=Users,DC=corp-pre,DC=com
encrypted.corp.secure.adapter.Password=HelloWorld1
Does the below code look right?
package com.company.boot;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and()
.formLogin();
}
#Configuration
protected static class AuthenticationConfiguration extends
GlobalAuthenticationConfigurerAdapter {
#Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource()
.url("ldap://ext_host:999/CN=Administrator,CN=Users,DC=ext-pre,DC=corp-pre,DC=com");
}
}
}
The above code only accommodates one ConnectionURL. How do I included the other ConnectionURL?
Just add it twice with different URL's. First it will authenticate against ldap://ext_host:999and on not finding will check in ldap://corp_host:888
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource()
.url("ldap://ext_host:999/CN=Administrator,CN=Users,DC=ext-pre,DC=corp-pre,DC=com");
auth
.ldapAuthentication()
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource()
.url("ldap://corp_host:888/CN=Administrator,CN=Users,DC=corp-pre,DC=com");
}
Related
I am using spring security to try and authenticate (and eventually authorize) using a client certificate. I already got it to authenticate using httpBasic.
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.POST, "/status", "/configure")
.access("hasRole('ADMIN')")
.antMatchers(HttpMethod.GET, "/**")
.permitAll()
.anyRequest()
.denyAll()
.and().x509()
.x509AuthenticationFilter(new AuthenticationFilter())
// .and().httpBasic()
.and()
.csrf().disable()
;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("dashboard.xxxx.yyy.zzz")
.password("{noop}password").roles("ADMIN");
}
}
I added a custom authentication filter so that I could toss in some logging, and both methods are returning null.
import java.security.cert.X509Certificate;
import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.web.authentication.preauth.x509.X509AuthenticationFilter;
public class AuthenticationFilter extends X509AuthenticationFilter {
private static Logger LOG = LogManager.getLogger(AuthenticationFilter.class);
public Object getPreAuthenticatedCredentials(HttpServletRequest request) {
LOG.info("" + super.getPreAuthenticatedCredentials(request));
return super.getPreAuthenticatedCredentials(request);
}
public Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
LOG.info("" + super.getPreAuthenticatedPrincipal(request));
return super.getPreAuthenticatedPrincipal(request);
}
}
Here is my tomcat server.xml connector.
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
keystoreFile="/opt/tomcat9/conf/dashboard.p12"
keystorePass="************" clientAuth="false"
sslProtocol="TLS" alias="dashboard"
sslEnabledProtocols="TLSv1.2"/>
Any ideas what I might be missing, or just doing incorrectly?
I am sending the client certificate via curl using --key and --cert. The --trace - option shows no errors.
Completely unrelated to Spring security.
The solution was to configure the server.xml to ask for the certificate.
<SSLHostConfig protocols="TLSv1.2" certificateVerification="required">
I'm trying to learn spring and create a web site where the authentication will be down via login page with angular passed to spring which needs to use ldap to authenticate. I figured I'd start on Spring site and walk through there guide but it seems to use deprecated code and it has an error.
I've been through several stackoverflow topics and google search but I'm not finding what I need.
src/main/java/hello/WebSecurityConfig.java
package hello;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.LdapShaPasswordEncoder;
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and()
.formLogin();
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource()
.url("ldap://localhost:8389/dc=springframework,dc=org")
.and()
.passwordCompare()
.passwordEncoder(new LdapShaPasswordEncoder())
.passwordAttribute("userPassword");
}
}
The problem is ".passwordEncoder(new LdapShaPasswordEncoder()) .passwordAttribute("userPassword")" LdapShaPasswordEncoder is deprecated and so it either what .passwordEncoder takes or the PasswordEncoder being returned by LdapShaPasswordEncoder. I have tried the BCrypt example I found on stack using BCryptPasswordEncoder but I still get an error from .passwordEncoder that it's not the correct PasswordEncoder org.springframework.security.authentication.encoding.PasswordEncoder vs org.springframework.security.crypto.password.PasswordEncoder
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource()
.url("ldap://localhost:8389/dc=springframework,dc=org")
.and()
.passwordCompare()
.passwordEncoder(new BCryptPasswordEncoder())
.passwordAttribute("userPassword");
}
^_^
I'm wprking on Spring security to secure a RESTFull API and Web App same time the problem is when i send a Rest request i receive an HTML page instead of receiving a JSON response, this is my configuration please can any one help me and check the configuration
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import com.example.jjjj.faces.MySimpleUrlAuthenticationSuccessHandler;
import com.example.jjjj.security.jwt.JwtAuthEntryPoint;
import com.example.jjjj.security.services.UserDetailsServiceImpl;
#EnableWebSecurity
public class MultiHttpSecurityConfig {
#Autowired
UserDetailsServiceImpl userDetailsService;
#Bean
public static AuthenticationSuccessHandler myAuthenticationSuccessHandler(){
return new MySimpleUrlAuthenticationSuccessHandler();
}
#Configuration
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Autowired
private JwtAuthEntryPoint unauthorizedHandler;
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().
authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// http
// .antMatcher("/api/**")
// .authorizeRequests()
// .anyRequest().hasRole("ADMIN")
// .and()
// .httpBasic();
}
}
#Configuration
#Order(1)
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN");
http.authorizeRequests().antMatchers("/company/**").hasRole("COMPANY_DATA_ENTRY_AGENT");
/*
http.cors().and().csrf().disable().
authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
*/
// require all requests to be authenticated except for the resources
http.authorizeRequests().antMatchers("/javax.faces.resource/**").permitAll().anyRequest().authenticated();
//http.authorizeRequests().antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')");
//http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
// login
http.formLogin().loginPage("/login.xhtml").successHandler(myAuthenticationSuccessHandler()).permitAll().failureUrl("/login.xhtml?error=true");
// logout
http.logout().logoutSuccessUrl("/login.xhtml");
// not needed as JSF 2.2 is implicitly protected against CSRF
http.csrf().disable();
// http
// .authorizeRequests()
// .anyRequest().authenticated()
// .and()
// .formLogin();
}
}
}
the configuration of the API works well alone and same for the Web Application configuration but when i want both of them to work well as the above configuration only one of them works which has the Order(1)
Please help !!!
Thank you.
Hello GUYS again !!!!
Just solved the problem
and this is the right configuration ^_^
#EnableWebSecurity
#EnableGlobalMethodSecurity(
prePostEnabled = true
)
public class MultiHttpSecurityConfig {
#Configuration
#Order
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Autowired
UserDetailsServiceImpl userDetailsService;
#Autowired
private JwtAuthEntryPoint unauthorizedHandler;
#Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().
authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// require all requests to be authenticated except for the resources
http.authorizeRequests().antMatchers("/javax.faces.resource/**").permitAll().anyRequest().authenticated();
}
}
#Configuration
#Order(1)
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
#Autowired
UserDetailsServiceImpl userDetailsService;
#Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){
return new MySimpleUrlAuthenticationSuccessHandler();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// not needed as JSF 2.2 is implicitly protected against CSRF
http.csrf().disable();
http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN");
http.authorizeRequests().antMatchers("/company/**").hasRole("COMPANY_DATA_ENTRY_AGENT");
//http.authorizeRequests().antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')");
//http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
// login
http.formLogin().loginPage("/login.xhtml").successHandler(myAuthenticationSuccessHandler()).permitAll().failureUrl("/login.xhtml?error=true");
// logout
http.logout().logoutSuccessUrl("/login.xhtml");
}
}
}
The solution is that this line must be the last antMatch ^_^
http.authorizeRequests().antMatchers("/javax.faces.resource/**").permitAll().anyRequest().authenticated();
Thank you so much GUYS
Good LUCK for all ^_^
I have this question already open. I need to know how can i allow spring-boot to allow .css and .js files for swagger to be loaded ?
Here is my WebSecurityConfig.java file
package com.path.to.project.config;
import com.path.to.project.jwt.JwtAuthenticationEntryPoint;
import com.path.to.project.jwt.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
#Autowired
private UserDetailsService userDetailsService;
#Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean
public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
return new JwtAuthenticationTokenFilter();
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.antMatchers("/register/**").permitAll()
.antMatchers("/swagger-ui*").permitAll()
.antMatchers("/v2/**").permitAll()
.antMatchers("/sysadmin/**").hasRole("SYSADMIN")
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/siteadmin/**").hasRole("SITEADMIN")
.anyRequest().authenticated();
// Custom JWT based security filter
httpSecurity
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
#Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
Just permit all access to your .css and .js paths (as you already did this with /register and other paths)
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers("/auth/**").permitAll()
.antMatchers("/register/**").permitAll()
.antMatchers("/swagger-ui*").permitAll()
.antMatchers("/v2/**").permitAll()
.antMatchers("/webjars/**").permitAll() //swagger ui files
.antMatchers("/sysadmin/**").hasRole("SYSADMIN")
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/siteadmin/**").hasRole("SITEADMIN")
.anyRequest().authenticated();
// Custom JWT based security filter
httpSecurity
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
I have set a up a spring boot (1.2.3) application with spring security and spring-ws. I have configured spring security to use .ldapAuthentication() for authentication in my WebSecurityConfigurerAdapter. I am trying to get the same spring security authenticationManager to authenticate my spring ws SOAP web services using ws-security usernametokens (plain text) in my WsConfigurerAdapter.
I have configured my WebSecurityConfigurerAdapter like this:
package za.co.switchx.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
#ConfigurationProperties(prefix="ldap.contextSource")
public LdapContextSource contextSource() {
LdapContextSource contextSource = new LdapContextSource();
return contextSource;
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userSearchBase("cn=Users,dc=SwitchX,dc=co,dc=za")
.userSearchFilter("(uid={0})")
.groupSearchBase("cn=Groups,dc=SwitchX,dc=co,dc=za")
.groupSearchFilter("(&(cn=*)(| (objectclass=groupofUniqueNames)(objectclass=orcldynamicgroup)))")
.contextSource(contextSource());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/ws/**").permitAll()
.anyRequest().authenticated()
.and()
.csrf().disable()
.httpBasic();
}
}
So then I went to configure my WsConfigurerAdapter like this:
package za.co.switchx.config;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
import org.springframework.ws.soap.security.xwss.XwsSecurityInterceptor;
import org.springframework.ws.soap.security.xwss.callback.SpringPlainTextPasswordValidationCallbackHandler;
import org.springframework.ws.server.EndpointInterceptor;
#EnableWs
#Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
#Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "ApplicantTypeService")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema applicantTypeServiceSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("ApplicantTypePort");
wsdl11Definition.setLocationUri("/ws/ApplicantTypeService");
wsdl11Definition.setTargetNamespace("http://switchx.co.za/services/applicant/types/applicant-type-web-service");
wsdl11Definition.setSchema(applicantTypeServiceSchema);
return wsdl11Definition;
}
#Bean
public XsdSchema applicantTypeSchema() {
return new SimpleXsdSchema(new ClassPathResource("xsd/ApplicantTypeService.xsd"));
}
#Bean
public XwsSecurityInterceptor securityInterceptor() {
XwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor();
securityInterceptor.setCallbackHandler(new SpringPlainTextPasswordValidationCallbackHandler());
securityInterceptor.setPolicyConfiguration(new ClassPathResource("securityPolicy.xml"));
return securityInterceptor;
}
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
interceptors.add(securityInterceptor());
}
}
If I use a SimplePasswordValidationCallbackHandler in the XwsSecurityInterceptor it does authenticate the ws usernametoken correctly, so I know there is nothing wrong with the ws-security section. And if I logon via http basic it authenticates my ldap user correctly so I know that works.
The problem is that when I try use my ldap user logon in the ws security usernametoken I get ERROR c.s.xml.wss.logging.impl.filter - WSS1408: UsernameToken Authentication Failed in the logs, so looks like its not using my global ldap authentication defined in the WebSecurityConfigAdapter
I cant seem to figure out how to get the SpringPlainTextPasswordValidationCallbackHandler (which is supposed to use spring security) in the XwsSecurityInterceptor to use the global authenticationManager, please help?? I have really been bashing my head against this for the last day but cant seem to win.
Ok I figured this out so though I would post for anyone trying this in the future.
I resolved this problem by changing my spring boot class to:
#SpringBootApplication
#EnableGlobalMethodSecurity(securedEnabled = true)
public class SwitchxApplication extends WebMvcConfigurerAdapter {
#SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(SwitchxApplication.class);
#Bean
public ApplicationSecurity applicationSecurity() {
return new ApplicationSecurity();
}
#Configuration
#Order(Ordered.HIGHEST_PRECEDENCE)
protected static class AuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter {
#Bean
#ConfigurationProperties(prefix="ldap.contextSource")
public LdapContextSource contextSource() {
LdapContextSource contextSource = new LdapContextSource();
return contextSource;
}
#Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userSearchBase("cn=Users,dc=Blah,dc=co,dc=za")
.userSearchFilter("(uid={0})")
.groupSearchBase("cn=Groups,dc=Blah,dc=co,dc=za")
.groupSearchFilter("(&(cn=*)(|(objectclass=groupofUniqueNames)(objectclass=orcldynamicgroup)))")
.contextSource(contextSource());
}
}
#Order(Ordered.LOWEST_PRECEDENCE - 8)
protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/ws/**").permitAll()
.anyRequest().authenticated()
.and()
.csrf().disable()
.httpBasic();
}
}
public static void main(String[] args) {
SpringApplication.run(SwitchxApplication.class, args);
}
}
And then made the following relevant changes in my WsConfigurerAdapter to:
#EnableWs
#Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
private static final Logger log = LoggerFactory.getLogger(WebServiceConfig.class);
#Autowired
private AuthenticationManager authenticationManager;
#Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
.....
.....
#Bean
public SpringPlainTextPasswordValidationCallbackHandler callbackHandler() {
SpringPlainTextPasswordValidationCallbackHandler callbackHandler = new SpringPlainTextPasswordValidationCallbackHandler();
try {
callbackHandler.setAuthenticationManager(authenticationManager);
} catch(Exception e) {
log.error(e.getMessage());
}
return callbackHandler;
}
#Bean
public XwsSecurityInterceptor securityInterceptor() {
XwsSecurityInterceptor securityInterceptor = new XwsSecurityInterceptor();
securityInterceptor.setCallbackHandler(callbackHandler());
securityInterceptor.setPolicyConfiguration(new ClassPathResource("securityPolicy.xml"));
return securityInterceptor;
}
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
interceptors.add(securityInterceptor());
}
}
So basically the end result is that for all /ws paths the basic http security is ignored but because of the security intercepter in the WS Config it will use a basic ws-security user name token to authenticate web service calls, allowing you to have both authentication mechanisms using spring security set up with ldap.
I hope this helps someone, was a bit tricky not finding of lot of documentation on the boot and java config documentation on this particular setup and stuff as it still relatively new. But after not getting this working, its pretty awesome and Im very impressed.