大多spring的那套东西,都支持注解和xml两种方式进行配置,而xml配置则通常比较麻烦,需要记住一大堆标签,通常提示也不是很到位,用xml配置需要我们对整个过程和各种标签都十分的熟悉,而这对于初学者通常都是比较难的一件事情,意味着学习时间需要更多。所以大多在项目中简单快捷的方式就是使用注解或者java类进行配置,更容易上手,springSecurity也提供了Java类配置的方式。
首先,在web.xml中配置一个过滤器,拦截url再交给spring来进行管理。
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
然后来个Java类来配置
package com.ezhiyang.springSecurity;
import org.springframework.beans.factory.annotation.Autowired;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
public void configGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER")
.and().withUser("admin").password("admin").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
}
这样就可以了,对SpringSecurity熟悉的可能就知道,我这样配置,其实和下面的xml配置其实是一样的,
-<http auto-config="true">
<intercept-url pattern="/user.jsp" access="ROLE_USER,ROLE_ADMIN"/>
<intercept-url pattern="/admin.jsp" access="ROLE_ADMIN"/>
<form-login/>
</http>
就是这样,就可以完成了java类来配置springSecurity的简单示例。