Manning.Spring.Security.in.Action.2020.10.pdf
参考代码: https://github.com/spring-projects/spring-security/tree/master/samples/javaconfig/hellomvc

引入依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>junit</groupId>
  4. <artifactId>junit</artifactId>
  5. <version>4.11</version>
  6. <scope>test</scope>
  7. </dependency>
  8. <!-- ... 引入 spring-security ... -->
  9. <dependency>
  10. <groupId>org.springframework.security</groupId>
  11. <artifactId>spring-security-web</artifactId>
  12. <version>${spring-security.version}</version>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.springframework.security</groupId>
  16. <artifactId>spring-security-config</artifactId>
  17. <version>${spring-security.version}</version>
  18. </dependency>
  19. <!-- 内嵌Tomcat -->
  20. <dependency>
  21. <groupId>org.apache.tomcat.embed</groupId>
  22. <artifactId>tomcat-embed-core</artifactId>
  23. <version>${tomcat.version}</version>
  24. <scope>provided</scope>
  25. </dependency>
  26. <!-- 引入 springmvc -->
  27. <dependency>
  28. <groupId>org.springframework</groupId>
  29. <artifactId>spring-webmvc</artifactId>
  30. <version>${spring.version}</version>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework</groupId>
  34. <artifactId>spring-jdbc</artifactId>
  35. <version>${spring.version}</version>
  36. </dependency>
  37. <!-- 引入logback,用于打印 log -->
  38. <dependency>
  39. <groupId>ch.qos.logback</groupId>
  40. <artifactId>logback-core</artifactId>
  41. <version>${logback.version}</version>
  42. </dependency>
  43. <dependency>
  44. <groupId>ch.qos.logback</groupId>
  45. <artifactId>logback-classic</artifactId>
  46. <version>${logback.version}</version>
  47. </dependency>
  48. </dependencies>

这里会遇到第一个坑,spring-security 会引入依赖 spring-context ,而在引入 spring-webmvc,也会引入 spring-context,这个时候会发生依赖冲突,所以在引入依赖的时候需要特别小心。需要查看版本。

初始化 spring-security

首先spring 应用的请求是先经过 DispatcherServlet 然后再分发给后面的系统,这里在经过 DispatcherServlet 之后,需要设置一个 filter 来将请求转发给 spring-security 做安全检查。 在官方的实例代码中,首先要新建一个类

package com.example.config;

import org.springframework.core.annotation.Order;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

@Order(2)
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}

就这样,什么都不用做,我们就把请求全部转发给了 spring-security 来进行检查。

spring-security 架构

那么spring-security 是如何工作的呢? 下图进行了说明
image.png

一个请求来到了 spring-security ,交给了 Authentication manager 处理
Authentication manager 使用 Authentication provider 进行用户的认证和授权

Authentication provider 会去执行认证登录的逻辑,首先它找到了 UserDetailsService 类查看相关 user 的信息,
然后,通过 Password encoder 校验密码,最后认证通过,返回一个认证过的实体类,存储在安全的上下文中,供随时使用。

实例

https://github.com/01x01/springmvc-with-spring-security