Spring Security是什么?

Spring Security是一套认证授权框架,支持认证模式如HTTP BASIC 认证头 (基于 IETF RFC-based 标准),HTTP Digest 认证头 ( IETF RFC-based 标准),Form-based authentication (用于简单的用户界面),OpenID 认证等,Spring Security使得当前系统可以快速集成这些验证机制亦或是实现自己的一套验证机制.

使用Spring Security

Spring Security3之后提供了Java Config的配置方式,但是我觉得xml方式比较容易理解其整体结构,所以本文都是基于xml配置的.

pom依赖

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>1.5.4.RELEASE</version>
  5. </parent>
  6. <dependencies>
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-security</artifactId>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-web</artifactId>
  14. </dependency>
  15. </dependencies>

由于使用了Spring Boot,所以需要使用@EnableWebSecurity注解启用Spring Security,并指明其配置文件为classpath下的spring-security.xml

  1. @Configuration
  2. @EnableWebSecurity
  3. @ImportResource(locations = "classpath:spring-security.xml")
  4. public class SecurityConfig {
  5. }

xml配置

在spring-security.xml中引入官方提供的命名空间,然后简单配置下,该配置大概意思是对所有请求的url拦截,必须有User权限的用户才能访问.

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:security="http://www.springframework.org/schema/security"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  6. http://www.springframework.org/schema/security
  7. http://www.springframework.org/schema/security/spring-security.xsd">
  8. <security:http >
  9. <security:intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
  10. <security:form-login/>
  11. <security:http-basic/>
  12. <security:logout/>
  13. </security:http>
  14. <security:authentication-manager>
  15. <security:authentication-provider>
  16. <security:user-service>
  17. <security:user name="user" password="123456" authorities="ROLE_USER"/>
  18. <security:user name="admin" password="123456" authorities="ROLE_USER, ROLE_ADMIN"/>
  19. </security:user-service>
  20. </security:authentication-provider>
  21. </security:authentication-manager>
  22. </beans>

访问测试

该页面为Spring Security自动生成的登录页面,当我们访问任何连接都会被重定向到该登录页面,输入user:123456登录后才能有权限访问.

分析

上述是一个简单的Demo,分析则是从这个Demo深入浅出.
1.Spring Security是如何拦截请求的?
传统的xml配置都会在web.xml里面配置如下过滤器.

  1. <filter>
  2. <filter-name>springSecurityFilterChain</filter-name>
  3. <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  4. </filter>
  5. <filter-mapping>
  6. <filter-name>springSecurityFilterChain</filter-name>
  7. <url-pattern>/*</url-pattern>
  8. </filter-mapping>

可以看出入口点就是该类,该类会从Spring容器中读取名称为springSecurityFilterChain的一个Filter实例,从而获取到对应代理的Filter.

  1. protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
  2. Filter delegate = wac.getBean(getTargetBeanName(), Filter.class);
  3. if (isTargetFilterLifecycle()) {
  4. delegate.init(getFilterConfig());
  5. }
  6. return delegate;
  7. }

然后在doFilter方法中调用该委托的filter,也就实现的拦截请求.

  1. protected void invokeDelegate(
  2. Filter delegate, ServletRequest request, ServletResponse response, FilterChain filterChain)
  3. throws ServletException, IOException {
  4. delegate.doFilter(request, response, filterChain);
  5. }

2. Spring Security拦截请求后是如何处理的?
打断点可以发现DelegatingFilterProxy实际上代理的是FilterChainProxy这个类,该类中有private List filterChains;全局变量,那么SecurityFilterChain为何物?

  1. public interface SecurityFilterChain {
  2. boolean matches(HttpServletRequest request);
  3. List<Filter> getFilters();
  4. }

从源码可以判断SecurityFilterChain是一套规则所对应的Filter链集合.再看源码getFilters,该方法会根据规则(也就是配置中的security:http标签)获取一个SecurityFilterChain中的一套对应规则的filter链.

  1. private List<Filter> getFilters(HttpServletRequest request) {
  2. for (SecurityFilterChain chain : filterChains) {
  3. if (chain.matches(request)) {
  4. return chain.getFilters();
  5. }
  6. }
  7. return null;
  8. }

最后在doFilterInternal方法中创建一个VirtualFilterChain类,调用其doFilter方法.VirtualFilterChain这个类很有意思,该类继承了FilterChain类,那么其就拥有了转交请求到指定filter的能力,另外其还拥有一套filter链List additionalFilters;,那么这个类就控制了整个Spring Security的执行流程,那么它是怎么实现的呢?
开始我以为是一个循环,然而看了源码才发现自己太low了.

  1. currentPosition++;
  2. Filter nextFilter = additionalFilters.get(currentPosition - 1);
  3. nextFilter.doFilter(request, response, this);

currentPosition与additionalFilters都是全局变量,其在调用filter链的时候每次都把自己本身在doFilter传值过去,每一个Filter链节点执行完毕后再返回VirtualFilterChain的doFilter方法,开启下一个节点执行.其结构如下面代码所示:

  1. interface IA{
  2. void doSomeThing(IAChain chain);
  3. }
  4. static class IAClass implements IA{
  5. @Override
  6. public void doSomeThing(IAChain chain) {
  7. System.out.println("i am IAClass");
  8. chain.doSomeThing();
  9. }
  10. }
  11. interface IAChain{
  12. void doSomeThing();
  13. }
  14. static class IAChainClass implements IAChain{
  15. List<IA> IAChains = new ArrayList<IA>();
  16. public IAChainClass() {
  17. IAChains.add(new IAClass());
  18. IAChains.add(new IAClass());
  19. IAChains.add(new IAClass());
  20. }
  21. int position = 0;
  22. @Override
  23. public void doSomeThing() {
  24. if (position == IAChains.size()) {
  25. System.out.println("end");
  26. return;
  27. }
  28. IA ia = IAChains.get(position++);
  29. ia.doSomeThing(this);
  30. }
  31. }

当调用iaChainClass.doSomeThing()输出

  1. i am IAClass
  2. i am IAClass
  3. i am IAClass
  4. end

调用链的实现还可以使用继承来实现,每次执行前先执行super()方法.
ok,下一章分析具体的Filter链中的节点,探究下Spring Security是如何进行用户认证与权限控制的.