Spring security + ldap
spring security 的java config方式配置
因为是在原有项目上配置spring security,之前spring配置使用的是xml方式,对于security的配置看网上大多数是使用java config的方式配置,所以想尝试采用java配置的方式
添加依赖
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>${springframework.version}</version>
</dependency>
spring security config
创建一个servlet filter,注册到springSecurityFilterChain
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userSearchBase("ou=users")
.userSearchFilter("(uid={0})")
.groupSearchBase("ou=groups")
.groupSearchFilter("memberUid={0}")
.contextSource()
.url("ldap://xxxxxxx")
.root("dc=xxxxxxx")
.managerDn("xxxxxxxxx")
.managerPassword("xxxxxxx");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login.jsp")
.and()
.authorizeRequests()
.antMatchers("/baselines/info").authenticated()
.antMatchers(HttpMethod.GET, "/baselines").hasRole("app-SW-functional")
.anyRequest().denyAll();
}
}
将filter注册到到应用
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}
最简单的配置按说就已经完成了,但是启动spring却启动不起来,提示filter启动失败
07-Dec-2018 21:03:38.676 SEVERE [RMI TCP Connection(4)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal One or more Filters failed to start. Full details will be found in the appropriate container log file
07-Dec-2018 21:03:38.676 SEVERE [RMI TCP Connection(4)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [] startup failed due to previous errors
找了很长时间的原因,跟书上的教程和网上的教程对比,都没发现问题在哪,最后从官方文档中看到如下信息,
就是说这个SecurityWebApplicationInitializer会添加ContextLoaderListener,但是因为是已有的xml配置项目,web.xml中已经添加了这个listener了,对内部逻辑不了解,上来就配置看起来是不行的。。。羞愧啊
后来尝试把web.xml中的这个listener去掉,发现原有的context都加载不起来了,最后放弃了java config的方式,用xml配置方式正常启动了