-
安全性是绝大多数应用的一个重要切面。Spring Security是一个安全框架,它基于Spring AOP和Servlet中的Filter
-
过滤Web请求
(1) Spring Security借助一系列Servlet Filter提供各种安全性功能
(2) 但是我们只需要配置一个Filter,当我们启用Web安全性的时候,会自动创建这些Filter
(3) web.xml配置
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="2.5"> <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> ... </web-app>
注意 <filter-name>必须配置为springSecurityFilterChain。因为接下来Spring Security会配置在Web安全性之中,这里会有一个springSecurityFilterChain的Filter bean,DelegatingFilterProxy会将过滤逻辑委托给它。
DelegatingFilterProxy是一个特殊的Servlet Filter,它的作用是将工作委托给一个Filter的实现类,这个实现类作为一个<bean>注册在Spring的上下文中
(4) Java Config 配置
public class SecurityWebInitializer extends AbstractSecurityWebApplicationInitializer { }
AbstractSecurityWebApplicationInitializer实现了WebApplicationInitializer,因此会被Spring自动发现,并用它在Web容器中注册DelegatingFilterProxy
(5) 无论使用web.xml还是JavaConfig配置DelegatingFilterProxy,它们都会拦截发往应用中的请求,并将请求委托给id为springSecurityFilterChain的bean;
SpringSecurityFilterChain是一个特殊的Filter,它可以连接任意其他的Filter。但是,无需知道细节,不需要显式声明SpringSecurityFilterChain以及它所链接在一起的其他Filter。当我们启用Web安全性时,会自动创建这些Filter
-
简单的Web安全性配置
(1) @EnableWebSecurity注解会启用Web安全功能,但是它必须配置在一个 实现了WebSecurityConfigurer的bean中 或 扩展了WebSecurityConfigurerAdapter(推荐)
(2) 如果使用了Spring MVC的话,推荐用 @EnableWebMVCSecurity 代替 @EnableWebSecurity
示例 SecurityConfig.java
@Configuration @EnableWebMvcSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { }
(3) 按照上面的示例进行配置,会导致没有人能够进入系统,因为 WebSecurityConfigurerAdapter的默认configure方法是
protected void configure(HttpSecurity http) throws Exception { logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity)."); http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin().and() .httpBasic();
}
所以为了在安全性上进行个性化定制,需要配置以下三个方法中的1个或几个:
configure(WebSecurity) 配置Filter链
configure(HttpSecurity) 配置如果通过拦截器保护请求
configure(AuthenticationManagerBuilder) 配置user-detail服务
网友评论