内容:《Spring Security实战》

第1部分 初识Spring Security

1.1 Spring Security简介

应用程序的安全性通常体现在两个方面:认证和授权。

  • 认证是确认某主体在某系统中是否合法、可用的过程。这里的主体既可以是登录系统的用户,也可以是接入的设备或者其他系统。
  • 授权是指当主体通过认证之后,是否允许其执行某项操作的过程。

这些概念并非Spring Security独有,而是应用安全的基本关注点。Spring Security可以帮助我们更便 捷地完成认证和授权。

Spring Securit y 支持广泛的认证技术,这些认证技术大多由第三方或相关标准组织开发。Sp ring Securit y 已经集成的认证技术如下:

  • HTTP BASIC authentication headers:一个基于IETF RFC的标准。 ◎ HTTP Digest authentication headers:一个基于IETF RFC的标准。
  • HTTP X.509 client certificate exchange:一个基于IETF RFC的标准。 ◎ LDAP:一种常见的跨平台身份验证方式。
  • Form-based authentication:用于简单的用户界面需求。
  • OpenID authentication:一种去中心化的身份认证方式。
  • Authentication based on pre-established request headers:类似于 Computer Associates SiteMinder,一种用户身份验证及授权的集中式安全基础方案。
  • Jasig Central Authentication Service:单点登录方案。
  • Transparent authentication context propagation for Remote Method Invocation(RMI)and HttpInvoker:一个Spring远程调用协议。
  • Automatic “remember-me” authentication:允许在指定到期时间前自行重新登录系统。 ◎ Anonymous authentication:允许匿名用户使用特定的身份安全访问资源。
  • Run-as authentication:允许在一个会话中变换用户身份的机制。
  • Java Authentication and Authorization Service:JAAS,Java验证和授权API。
  • Java EE container authentication:允许系统继续使用容器管理这种身份验证方式。
  • Kerberos:一种使用对称密钥机制,允许客户端与服务器相互确认身份的认证协议。

除此之外,Spring Security还引入了一些第三方包,用于支持更多的认证技术,如JOSSO等。如果所有这些技术都无法满足需求,则Spring Security允许我们编写自己的认证技术。因此,在绝大部分情况下,当我们有Java应用安全方面的需求时,选择Spring Security往往是正确而有效的。

1.2 创建一个简单的Spring Security项目

本节创建一个简单的Spring Security项目,带领大家初步领略Spring Security带来的便利。下面我们就完整地“走”一遍创建项目的流程。
通过Intellij IDEA创建Spring Boot项目的方式有许多种,其中最简单的方式就是使用Spring Initializr工具,省略了在https://start.spring.io中生成并导入Intellij IDEA的过程。Eclipse也提供了一个可以实现 类似功能的插件:STS(Spring Tool Suite),感兴趣的读者可以自行了解。此处我们单击“Next”按钮进 入下一个页面,如图1-1所示。
阿里:https://start.aliyun.com/

Spring Initializr创建项目,选择 Security作为构建Spring Security项目的最小依赖,选择Spring Web作为Spring Boot构建Web应用的核心依赖。
image.png
查看Pom文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.5.4</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>spring-demo</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>spring-demo</name>
  15. <description>spring-demo</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-security</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28. </dependencies>
  29. <build>
  30. <plugins>
  31. <plugin>
  32. <groupId>org.springframework.boot</groupId>
  33. <artifactId>spring-boot-maven-plugin</artifactId>
  34. </plugin>
  35. </plugins>
  36. </build>
  37. </project>

下面打开程序的入口类SpringDemoApplication,声明一个hello路由。

  1. @RestController
  2. @SpringBootApplication
  3. public class SpringDemoApplication {
  4. @GetMapping("/")
  5. public String hello() {
  6. return "hello,spring security";
  7. }
  8. public static void main(String[] args) {
  9. SpringApplication.run(SpringDemoApplication.class, args);
  10. }
  11. }

启动程序,输入http://localhost:8080 可以看到登陆框
image.png
在引入Spring Security项目之后,虽然没有进行任何相关的配置或编码,但Spring Security有一个默认的运行状态,要求在经过HTTP基本认证后才能访问对应的URL资源,其默认使用的用户名为user,密码则是动态生成并打印到控制台的一串随机码。翻看控制台的打印信息,可以看到如图所示的输出。
image.png
4b6fe046-dd65-4cb5-acf2-edc3a4e84eb6

输入用户名和密码后,单击“登录”按钮即可成功访问hello页面,如图所示。
当然,右HTTP基本认证中,用户名和密码都是可以配置的,最常见的就是在resources下的配置文件中修改。
打开application.properties,输入以下配置信息:

  1. server.port=18080
  2. spring.security.user.name=admin
  3. spring.security.user.password=admin

重新启动程序,发现控制台不再打印默认密码串了,此时使用我们自定义的用户名和密码即可登录。
事实上,绝大部分Web应用都不会选择HTTP基本认证这种认证方式,除安全性差、无法携带cookie等因素外,灵活性不足也是它的一个主要缺点。通常大家更愿意选择表单认证,自己实现表单 登录页和验证逻辑,从而提高安全性。

我的页面返回的是错误

  1. Whitelabel Error Page
  2. This application has no explicit mapping for /error, so you are seeing this as a fallback.
  3. Thu Sep 23 10:50:53 CST 2021
  4. There was an unexpected error (type=Not Found, status=404).
  5. 原因是启动类上没有添加注解:@RestControler

第2章 表单认证

2.1 默认表单认证

首先,新建一个configuration包用于存放通用配置;然后,新建一个WebSecurityConfig类,使其继承WebSecurityConfigurerAdapter

  1. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  2. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  3. @EnableWebSecurity
  4. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  5. }

接着查看WebSecurityConfigurerAdapter类对configure(HttpSecurity http)的定义。

  1. protected void configure(HttpSecurity http) throws Exception {
  2. this.logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");
  3. http.authorizeRequests((requests) -> {
  4. ((AuthorizedUrl)requests.anyRequest()).authenticated();
  5. });
  6. http.formLogin();
  7. http.httpBasic();
  8. }

可以看到WebSecurityConfigurerAdapter已经默认声明了一些安全特性:
◎ 验证所有请求。
◎ 允许用户使用表单登录进行身份验证(Spring Security提供了一个简单的表单登录页面)。
◎ 允许用户使用HTTP基本认证。
现在重启服务,应用新的安全配置。可以预见,在下次访问localhost:8080时,系统会要求我们进行表单认证。

结果很意外,无论怎么刷新,都无法看到表单登录页,为什么呢?我们可以从浏览器的开发者工具中找到蛛丝马迹(在Chrome浏览器中可以按快捷键F12调出开发者工具),如图所示。 可以清楚地看到,浏览器发出的请求头中自动携带Authorization属性,由于Spring Security的配置刚好同时支持HTTP基本认证,所以并不需要在表单中重新登录。 这实际上属于浏览器的默认行为,只要在HTTP基本认证中成功认证过,便会自动记住一段时间,也就是说,可以跳过登录直接访问系统资源。那么如何避免这种情况的发生呢?在IE浏览器中, 可以在控制台执行document.execCommand(“ClearAut hent icat ionCache”)语句清除HTTP基本认证缓存,但这种方法在Chrome浏览器中并不适用。建议调试时直接使用浏览器的无痕模式,简单方便,可以避免很多缓存问题(在Windows下的Chrome浏览器中,可用组合键 Ctrl+Shift+n 打开浏览器的无痕 模式;在mac下的Chrome浏览器中,可用组合键Command+Shift+n打开浏览器的无痕模式)。
经过一些小插曲,我们终于成功进入表单登录页,如图2-3所示。

2.2 自定义表单登录页

1.初步配置自定义表单登录页
虽然自动生成的表单登录页可以方便、快速地启动,但是大多数应用程序更希望提供自己的表单 登录页,此时就需要覆写configure方法。

  1. @EnableWebSecurity
  2. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Override
  4. protected void configure(HttpSecurity http) throws Exception {
  5. http.authorizeRequests()
  6. .anyRequest().authenticated()
  7. .and()
  8. .formLogin()
  9. .loginPage("/myLogin.html")
  10. //使登陆页不设限访问
  11. .permitAll()
  12. .and()
  13. .csrf().disable();
  14. }
  15. }

2.认识HttpSecurity
HttpSecurity实际上对应了=Spring Security命名空间配置方式中XML文件内的标签,允许我们为特 定的HTTP请求配置安全策略。

在XML文件中,声明大量配置早已司空见惯;但在Java配置中,按照传统的方式,我们需要这样来调用。

  1. @EnableWebSecurity
  2. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Override
  4. protected void configure(HttpSecurity http) throws Exception {
  5. ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry urlRegistry = http.authorizeRequests();
  6. ExpressionUrlAuthorizationConfigurer.AuthorizedUrl authorizedUrl = (ExpressionUrlAuthorizationConfigurer.AuthorizedUrl) urlRegistry.anyRequest();
  7. authorizedUrl.authenticated();
  8. //more
  9. FormLoginConfigurer<HttpSecurity> formLoginConfigurer = http.formLogin();
  10. formLoginConfigurer.loginPage("/myLogin.html");
  11. formLoginConfigurer.permitAll();
  12. //mort
  13. }
  14. }

可以想象出这是多么烦琐且令人痛苦的一件事。HttpSecurity首先被设计为链式调用,在执行每个方法后,都会返回一个预期的上下文,便于连续调用。我们不需要关心每个方法究竟返回了什么、如何进行下一个配置等细节。
HttpSecurity提供了很多配置相关的方法,分别对应命名空间配置中的子标签。例如,authorizeRequests()、formLogin()、httpBasic()和 csrf()分别对应、、和标签。调用这些方法之后,除非使用and()方法结束当前标签,上下文才会回到HttpSecurity,否则链式调用的上下文将自动进入对应标签域。

authorizeRequests()方法实际上返回了一个URL拦截注册器,我们可以调用它提供的anyanyRequest()、antMatchers()和regexMatchers()等方法来匹配系统的URL,并为其指定安全策略。

formLogin()方法和httpBasic()方法都声明了需要Spring Security提供的表单认证方式,分别返回对应的配置器。其中,formLogin().loginPage(“/myLogin.html”)指定自定义的登录页/myLogin.html,同时,Spring Security会用/myLogin.html注册一个POST路由,用于接收登录请求。

csrf()方法是Spring Security提供的跨站请求伪造防护功能,当我们继承WebSecurityConfigurerAdapter时会默认开启csrf()方法。关于csrf()方法的更多内容会在后面的章节专门探讨,以使测试进程更加顺利。

重新启动服务后再次访问localhost:8080,页面会自动跳转到localhost:8080/myLogin.html。由于/myLogin.html无法定位到页面资源,所以会显示一个404页面,如图所示。
image.png

3.编写表单登录页
表单登录页的代码如下所示。

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html:charset=utf-8"/>
  5. <title>登陆</title>
  6. <style>
  7. /*some style*/
  8. </style>
  9. </head>
  10. <body>
  11. <div class="login">
  12. <h2>Acced Form</h2>
  13. <div class="login-top">
  14. <h1>LOGIN FORM</h1>
  15. <form action="myLogin.html" method="post">
  16. <input type="text" name="username" placeholder="username"/>
  17. <input type="password" name="password" placeholder="password"/>
  18. <div class="forgot">
  19. <a href="#">forgot Password</a>
  20. <input type="submit" value="Login">
  21. </div>
  22. </form>
  23. </div>
  24. <div class="login-botton">
  25. <h3>New User &nbsp;<a href="#">Register &nbsp Here</a></h3>
  26. </div>
  27. </div>
  28. </body>
  29. </html>

myLogin.html是开源模板,这里仅对其进行一些简单修改。因为篇幅有限,所以CSS样式部分已被截取。

在表单登录页中,仅有一个表单,用户名和密码分别为username和password,并以POST的方式提交到/myLogin.html。
我们将其命名为myLogin.html,放置在resources/static/下。重启服务,再次访问localhost:8080,即 可看到自定义的表单登录页,如图所示。

myLogin.html是开源模板,这里仅对其进行一些简单修改。因为篇幅有限,所以CSS样式部分已被截取。
在表单登录页中,仅有一个表单,用户名和密码分别为username和password,并以POST的方式提交到/myLogin.html。
我们将其命名为myLogin.html,放置在resources/static/下。重启服务,再次访问localhost:8080,即 可看到自定义的表单登录页。

输入正确的用户名和密码后,单击“ Login”按钮,即可成功跳转。

4.其他表单配置项
在自定义表单登录页之后,处理登录请求的URL也会相应改变。如何自定义URL呢?很简单,Spring Security在表单定制里提供了相应的支持。

  1. @EnableWebSecurity
  2. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Override
  4. protected void configure(HttpSecurity http) throws Exception {
  5. http.authorizeRequests()
  6. .anyRequest().authenticated()
  7. .and()
  8. .formLogin()
  9. .loginPage("/myLogin.html")
  10. .loginProcessingUrl("/login")
  11. //使登陆页不设限访问
  12. .permitAll()
  13. .and()
  14. .csrf().disable();
  15. }
  16. }

此时,有些读者可能会有疑问,因为按照惯例,在发送登录请求并认证成功之后,页面会跳转回原访问页。在某些系统中的确是跳转回原访问页的,但在部分前后端完全分离、仅靠JSON完成所有交互的系统中,一般会在登录时返回一段JSON数据,告知前端成功登录成功与否,由前端决定如何处理后续逻辑,而非由服务器主动执行页面跳转。这在Spring Security中同样可以实现。

  1. @EnableWebSecurity
  2. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Override
  4. protected void configure(HttpSecurity http) throws Exception {
  5. http.authorizeRequests()
  6. .anyRequest().authenticated()
  7. .and()
  8. .formLogin()
  9. .loginPage("/myLogin.html")
  10. //指定处理登陆请求的路径
  11. .loginProcessingUrl("/login")
  12. //指定处理登陆成功时的处理逻辑
  13. .successHandler(new AuthenticationSuccessHandler() {
  14. @Override
  15. public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
  16. httpServletResponse.setContentType("application/json;charset=UTF-8");
  17. PrintWriter out = httpServletResponse.getWriter();
  18. out.write("{\"error_code\":\"0\",\"meeeage\":\"欢迎登陆系统\"}");
  19. }
  20. })
  21. //指定登陆失败时的处理逻辑
  22. .failureHandler(new AuthenticationFailureHandler() {
  23. @Override
  24. public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
  25. httpServletResponse.setContentType("application/json;charset=UTF-8");
  26. httpServletResponse.setStatus(401);
  27. PrintWriter out = httpServletResponse.getWriter();
  28. //输出失败的原因
  29. out.write("{\"error_code\":\"401\",\"name\":\"" + e.getClass() + "\",\"message\":\"" + e.getMessage() + "\"}");
  30. }
  31. })
  32. .and()
  33. .csrf().disable();
  34. }
  35. }

第3章 认证与授权

在第2章中,我们沿用了Spring Security默认的安全机制:仅有一个用户,仅有一种角色。在实 际开发中,这自然是无法满足需求的。本章将更加深入地对Spring Security迚行配置,且初步使用授权机制。

3.1 默认数据库模型的认证与授权

3.1.1 资源准备

首先,在controller包下新建三个控制器,如图3-1所示。

其次,分别建立一些测试路由。

  1. @RestController
  2. @RequestMapping("/admin/api")
  3. public class AdminController {
  4. @GetMapping("hello")
  5. public String hello() {
  6. return "hello,admin";
  7. }
  8. }
  9. @RestController
  10. @RequestMapping("/app/api")
  11. public class AppController {
  12. @GetMapping("hello")
  13. public String hello() {
  14. return "hello,app";
  15. }
  16. }
  17. @RestController
  18. @RequestMapping("/user/api")
  19. public class UserController {
  20. @GetMapping("hello")
  21. public String hello() {
  22. return "hello,user";
  23. }
  24. }

假设在/admin/api/下的内容是系统后台管理相关的 API,在/app/api 下的内容是面向客户端公开访 问的API,在/user/api/下的内容是用户操作自身数据相关的API;显然,/admin/api必须拥有管理员权限 才能进行操作,而/user/ap i必须在用户登录后才能进行操作。

3.1.2 资源授权的配置

为了能正常访问前面的路由,我们需要进一步地配置Spring Security。

  1. @EnableWebSecurity
  2. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Override
  4. protected void configure(HttpSecurity http) throws Exception {
  5. http.authorizeRequests()
  6. .antMatchers("/admin/api/**").hasRole("ADMIN")
  7. .antMatchers("/user/api/**").hasRole("USER")
  8. .antMatchers("/app/api/**").permitAll()
  9. .anyRequest().authenticated()
  10. .and()
  11. .formLogin();
  12. }
  13. }

antMatchers()是一个采用ANT模式的URL匹配器。ANT模式使用?匹配任意单个字符,使用匹配0或任意数量的字符,使用*匹配0或者更多的目录。antMatchers(“/admin/api/“)相当于匹配了/admin/api/下的所有API。此处我们指定当其必须为ADMIN角色时才能访问,/user/api/与之同理。/app/api/下的API会调用permitAll()公开其权限。

授权相关的配置看起来并不复杂,但似乎缺少了什么?这里暂且忽略。
重启服务,尝试访问localhost:8080/app/api/hello,页面打印“hello,app”,验证了/app/api/下的服务确实是权限公开的。接着访问localhost:8080/user/api/hello,这次需要登录了。我们尝试输入前面在 application.properties中定义的用户名和密码,登录之后,页面打印“hello,user”。然而,我们并没有user 用户,为什么可以成功访问路由呢?为了验证不是授权环节出现了问题,我们尝试访问localhost:8080/admin/api/hello,如图3-2所示。

页面显示403错误,表示该用户授权失败(401代表该用户认证失败)。也就是说,本次访问已经通过了认证环节,只是在授权的时候被驳回了。认证环节是没有问题的,因为Spring Security默认的用户角色正是user。

HTTP状态码(HTTP Status Code)是由RFC 2616定义的一种用来表示一个HTTP请求响应状态的规范,由3位数字组成。通常用2XX表示本次操作成功,用4XX表示是客户端导致的失败,用5XX表示是服务器引起的错误。

3.1.3 基于内存的多用户支持

到目前为止,我们仍然只有一个可登录的用户,怎样引入多用户呢?非常简单,我们只需实现一个自定义的UserDetailsService
�即可。

  1. @Bean
  2. public UserDetailsService userDetailsService() {
  3. InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
  4. manager.createUser(User.withUsername("user").password("123").roles("USER").build());
  5. manager.createUser(User.withUsername("admin").password("123").roles("USER", "ADMIN").build());
  6. return manager;
  7. }

为其添加一个@bean注解,便可被Spring Security发现并使用。Spring Security支持各种来源的用户数据,包括内存、数据库、LDAP等。它们被抽象为一个UserDetailsService接口,任何实现了UserDetailsService 接口的对象都可以作为认证数据源。在这种设计模式下,Spring Security显得尤为灵活。

InMemoryUserDetailsManager是UserDetailsService接口中的一个实现类,它将用户数据源寄存在内存里,在一些不需要引入数据库这种重数据源的系统中很有帮助。
这里仅仅调用createUser生成两个用户,并赋予相应的角色。它会工作得很好,多次重启服务 也不会出现问题。为什么要强调多次重启服务呢?稍后揭晓答案。

3.1.4 基于默认数据库模型的认证与授权

除了InMemoryUserDetailsManager,Spring Security还提供另一个UserDetailsService实现类: JdbcUserDetailsManager。

JdbcUserDetailsManager帮助我们以JDBC的方式对接数据库和Spring Security,它设定了一个默认的数据库模型,只要遵从这个模型,在简便性上,JdbcUserDetailsManager甚至可以媲美InMemoryUserDetailsManager。

1.数据库准备
M y SQL的安装这里不赘述,首先在工程中引入JDBC和MySQL两个必要依赖。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-jdbc</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>mysql</groupId>
  7. <artifactId>mysql-connector-java</artifactId>
  8. <scope>runtime</scope>
  9. </dependency>

接着在application.properties中配置数据库连接参数。

  1. spring.datasource.url=jdbc:mysql://39.100.127.235:13306/springDemo?userUnicode=true&characterEncoding=utf-8&userSSL=false
  2. spring.datasource.username=root
  3. spring.datasource.password=root

这里连接的数据库名为springDemo(不配置driverClassName也不会出现问题,因为Spring Boot会自动根据URL去推断)。用户名、密码分别为root和123456,读者可根据实际情况,自行修改。

前面介绍过,JdbcUserDetailsManager设定了一个默认的数据库模型,Spring Security将该模型定义在/org/springframework/security/core/userdetails/jdbc/users.ddl内。

  1. create table users
  2. (
  3. username varchar(50) not null primary key,
  4. password varchar(500) not null,
  5. enabled boolean not null
  6. );
  7. create table authorities
  8. (
  9. username varchar(50) not null,
  10. authority varchar(50) not null,
  11. constraint fk_authorities_users foreign key (username) references users (username)
  12. );
  13. create unique index ix_auth_username on authorities (username, authority);

JdbcUserDetailsManager需要两个表,其中users表用来存放用户名、密码和是否可用三个信息, authorities表用来存放用户名及其权限的对应关系。

2.编码实现
下面构建一个JdbcUserDetailsManager实例,让Spring Security使用数据库来管理用户。

  1. import org.apache.tomcat.jdbc.pool.DataSource;
  2. @Autowired
  3. private DataSource dataSource;
  4. @Override
  5. @Bean
  6. public UserDetailsService userDetailsService() {
  7. JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
  8. manager.setDataSource(dataSource);
  9. manager.createUser(User.withUsername("user").password("123").roles("USER").build());
  10. manager.createUser(User.withUsername("admin").password("123").roles("USER", "ADMIN").build());
  11. return manager;
  12. }

JdbcUserDetailsManager与InMemoryUserDetailsManager在用法上没有太大区别,只是多了设置DataSource的环节。Spring Security 通过 DataSource 执行设定好的命令。例如,此处的createUser函数实际上就是执行了下面的SQL语句。

  1. INSERT INTO users(username,password,enabled) values(?,?,?)

查看JdbcUserDetailsManager的源代码可以看到更多定义好的SQL语句,诸如deleteUserSql、updateUserSql等,这些都是JdbcUserDetailsManager与数据库实际交互的形式。当然, JdbcUserDetailsManager也允许我们在特殊情况下自定义这些SQL语句,如有必要,调用对应的 setXxxSql方法即可。

现在重启服务,看看在数据库中Spring Security生成了哪些数据。

authorities 表的authority 字段存放的是前面设定的角色,只是会被添上“ROLE_”前缀。下面尝试
通过SQL命令创建一个测试账号。

  1. INSERT INTO users values(“test”,“123”,true);
  2. INSERT INTO authorities values("test","ROLE_USER");

清空缓存并使用测试账号访问系统,发现可以访问user路由,但不能访问admin路由,与预期的行 为一致。
到目前为止,一切都工作得很好,但是只要我们重启服务,应用就会报错。这是因为users表在创建语句时,username字段为主键,主键是唯一不重复的,但重启服务后会再次创建admin和user,导致数据库报错(在内存数据源上不会出现这种问题,因为重启服务后会清空username字段中的内容)。 所以如果需要在服务启动时便生成部分用户,那么建议先判断用户名是否存在。

  1. @Bean
  2. public UserDetailsService userDetailsService() {
  3. JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
  4. manager.setDataSource(dataSource);
  5. if (!manager.userExists("user")) {
  6. manager.createUser(User.withUsername("user").password("123").roles("USER").build());
  7. }
  8. if (!manager.userExists("admin")) {
  9. manager.createUser(User.withUsername("admin").password("123").roles("USER", "ADMIN").build());
  10. }
  11. return manager;
  12. }

在2.2节的自定义表单登录页中,WebSecurityConfigurer Adapter定义了三个configure。

  1. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  2. this.disableLocalConfigureAuthenticationBldr = true;
  3. }
  4. public void configure(WebSecurity web) throws Exception {
  5. }
  6. protected void configure(HttpSecurity http) throws Exception {
  7. this.logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");
  8. http.authorizeRequests((requests) -> {
  9. ((AuthorizedUrl)requests.anyRequest()).authenticated();
  10. });
  11. http.formLogin();
  12. http.httpBasic();
  13. }

我们只用到了一个参数,用来接收HttpSecurity对象的配置方法。另外两个参数也有各自的用途,其中,AuthenticationManagerBuilder的configure同样允许我们配置认证用户。

  1. @EnableWebSecurity
  2. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  3. @Override
  4. protected void configure(HttpSecurity http) throws Exception {
  5. http.authorizeRequests()
  6. .antMatchers("/admin/api/**").hasRole("ADMIN")
  7. .antMatchers("/user/api/**").hasRole("USER")
  8. .antMatchers("/app/api/**").permitAll()
  9. .anyRequest().authenticated()
  10. .and()
  11. .formLogin();
  12. }
  13. @Override
  14. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  15. auth.inMemoryAuthentication()
  16. .withUser("user").password("123").roles("user")
  17. .and()
  18. .withUser("admin").password("123").roles("admin");
  19. }

使用方法大同小异,这里不再赘述。
当使用Spring Security默认数据库模型应对各种用户系统时,难免灵活性欠佳。尤其是在对现有的 系统做Spring Security嵌入时,原本的用户数据已经固定,为了适配Spring Security而在数据库层面进行 修改显然得不偿失。强大而灵活的Spring Security对这方面进行了改进。

错误说明-java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id “null”

  1. java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"

Spring security 5.0中新增了多种加密方式,也改变了默认的密码格式,不再允许使用明文。所以要进行相应的加密处理。

  1. WebSecurityConfig.java文件
  2. 登陆验证时
  3. @Override
  4. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  5. //读取时使用密码加密
  6. auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
  7. }
  8. 存储加密时:新增用户时加密
  9. @Bean
  10. public UserDetailsService userDetailsService() {
  11. JdbcUserDetailsManager manager = new JdbcUserDetailsManager();
  12. manager.setDataSource(dataSource);
  13. if (!manager.userExists("user")) {
  14. manager.createUser(User.withUsername("user").password(passwordEncoder.encode("123")).roles("USER").build());
  15. }
  16. if (!manager.userExists("admin")) {
  17. manager.createUser(User.withUsername("admin").password(passwordEncoder.encode("123")).roles("USER", "ADMIN").build());
  18. }
  19. return manager;
  20. }
  21. }

3.2 自定义数据库模型的认证与授权

让Spring Security适应系统,而非让系统适应Spring Security,是Spring Security框架开发者和使用者的共识。

下面我们将使用自定义数据库模型接入Spring Security,数据库依然是MySQL,持久层框架则选 用MyBatis(倾向于使用JPA的读者也可以自行选型,它们在Spring Security部分的实践是一样的)。旁枝末节的知识会点到即止,我们重点介绍Spring Security相关的内容,所以期望读者自行阅读相关资料,也可以选择暂时略过。

3.2.1 实现UserDetails

在3.1节,我们使用了InMemoryUserDetailsManager和JdbcUserDetailsManager两个UserDetailsService实现类。生效方式也很简单,只需加入Spring的IoC容器,就会被SpringSecurity自动发现并使用。自定义数据库结构实际上也仅需实现一个自定义的UserDetailsService。

UserDetailsService仅定义了一个loadUserByUsername方法,用于获取一个UserDetails对象。 UserDetails对象包含了一系列在验证时会用到的信息,包括用户名、密码、权限以及其他信息,Spring Security会根据这些信息判定验证是否成功。

  1. public interface UserDetails extends Serializable {
  2. Collection<? extends GrantedAuthority> getAuthorities();
  3. String getPassword();
  4. String getUsername();
  5. boolean isAccountNonExpired();
  6. boolean isAccountNonLocked();
  7. boolean isCredentialsNonExpired();
  8. boolean isEnabled();
  9. }

也就是说,不管数据库结构如何变化,只要能构造一个UserDetails即可,下面就来实现这个过程。

1.数据库准备
设计一个自定义的数据库结构。

  1. create table users
  2. (
  3. id bigint(20) not null auto_increment,
  4. username varchar(50) not null,
  5. password varchar(64) not null,
  6. enabled tinyint(4) not null default '1' comment '用户是否可用',
  7. roles text CHARACTER SET utf8 comment '用户角色,多个角色之间用逗号隔开',
  8. primary key (id),
  9. KEY username (username)
  10. );

我们把用户信息和角色放在同一张表中,不再是Spring Security默认的分开形式。roles字段设定为 text 类型,多个角色之间用逗号隔开。建议在username字段上建立索引,以提高搜索速度。
插入两条数据

  1. insert into users (username, password, roles) values ('admin','123','ROLE_ADMIN,ROLE_USER');
  2. insert into users (username, password, roles) values ('user','123','ROLE_USER');

2.编码实现
当数据库结构和数据准备完毕时,即可编写对应的User实体。
�

  1. public class User {
  2. private Long id;
  3. private String username;
  4. private String password;
  5. private String roles;
  6. private boolean enabled;
  7. //get and set
  8. }

让User实体继承UserDetails

  1. public class User implements UserDetails {
  2. private Long id;
  3. private String username;
  4. private String password;
  5. private String roles;
  6. private boolean enabled;
  7. private List<GrantedAuthority> authorities;
  8. @Override
  9. public boolean isAccountNonExpired() {
  10. return true;
  11. }
  12. @Override
  13. public boolean isAccountNonLocked() {
  14. return true;
  15. }
  16. @Override
  17. public boolean isCredentialsNonExpired() {
  18. return true;
  19. }
  20. @Override
  21. public Collection<? extends GrantedAuthority> getAuthorities() {
  22. return this.authorities;
  23. }
  24. }

实现UserDetails定义的几个方法:
◎ isAccountNonExpired、isAccountNonLocked 和 isCredentialsNonExpired 暂且用不到,统一返回 true,否则Spring Security会认为账号异常。
◎ isEnabled对应enable字段,将其代入即可。
◎ getAuthorities方法本身对应的是roles字段,但由于结构不一致,所以此处新建一个,并在后续 进行填充。

3.2.2 实现UserDetailsService

当准备好UserDetails之后,使用数据库持久层框架读取数据并填充对象。首先引入MyBatis。

  1. <dependency>
  2. <groupId>org.mybatis.spring.boot</groupId>
  3. <artifactId>mybatis-spring-boot-starter</artifactId>
  4. <version>1.3.1</version>
  5. </dependency>

前面在配置文件中曾写过数据库相关的配置,这里沿用即可。
�接下来在入口类中用@MapperScan指定MyBatis要扫描的映射文件目录。

  1. @MapperScan("com.example.springdemo.mapper")
  2. @SpringBootApplication
  3. public class SpringDemoApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(SpringDemoApplication.class, args);
  6. }
  7. }

编写对应的Mapper

  1. @Component
  2. public interface UserMapper {
  3. @Select("Select * FROM users WHERE username=#{username}")
  4. User findByUserName(@Param("username") String username);
  5. }

与MyBatis相关的内容不再赘述,没有接触过且感兴趣的读者可以自行学习相关知识,这里仅提 供一个通过用户名查找用户的方法。
2.编码实现
当数据持久层准备完成后,我们开始编写UserDetailsService。

  1. @Service
  2. public class MyUserDetailsService implements UserDetailsService {
  3. @Autowired
  4. private UserMapper userMapper;
  5. @Override
  6. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  7. //从数据库尝试读取该用户
  8. User user = userMapper.findByUserName(username);
  9. //用户不存在,抛出异常
  10. if (user == null) {
  11. throw new UsernameNotFoundException("用户不存在");
  12. }
  13. //将数据库形式的roles解析为UserDEtails的权限集
  14. //AuthorityUtils.commaSeparatedStringToAuthorityList是Spring Security提供的,该方法用于将逗号隔开的权限集字符串切割成可用权限对象列表
  15. //当前也可以自己实现,如用分号来隔开等,参考generateAuthorities
  16. user.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()));
  17. return user;
  18. }
  19. private List<GrantedAuthority> generateAuthorities(String roles) {
  20. List<GrantedAuthority> authorities = new ArrayList<>();
  21. String[] roleArray = roles.split(";");
  22. if (roles != null && "".equals(roles)) {
  23. for (String role : roleArray) {
  24. authorities.add(new SimpleGrantedAuthority(role));
  25. }
  26. }
  27. return authorities;
  28. }
  29. }

其中,SimpleGrantedAuthority是GrantedAuthority的一个实现类。Spring Security的权限几乎是用SimpleGrantedAuthority生成的,只要注意每种角色对应一个GrantedAuthority即可。另外,一定要在自己的UserDetailsService实现类上加入@Service注解,以便被Spring Security自动发现。

至此,我们就实现了Spring Security的自定义数据库结构认证。有些读者可能会有疑问,为什么在数据库中的角色总是要添加“ROLE”前缀,在配置时却并没有“ROLE”前缀呢?
因为在hasRole判断时才会添加上的。如果不想使用,可以使用hasAuthority方法。

第4章 实现图形验证码

在验证用户名和密码之前,引入辅助验证可有效防范暴力试错,图形验证码就是简单且行之有效的一种辅助验证方式。下面将使用过滤器和自定义认证两种方式实现图形验证码功能。

4.1 使用过滤器实现图形验证码

验证码(CAPTCHA)的全称是Completely Automated Public Turing test to tell Computers and Humans Apart,翻译过来就是“全自动区分计算机和人类的图灵测试”。通俗地讲,验证码就是为了防止恶意用户暴力重试而设置的。不管是用户注册、用户登录,还是论坛发帖,如果不加以限制,一旦某些恶意用户利用计算机发起无限重试,就很容易使系统遭受破坏。

4.1.1 自定义过滤器

在Spring Security中,实现验证码校验的方式有很多种,最简单的方式就是自定义一个专门处理验证码逻辑的过滤器,将其添加到Spring Security过滤器链的合适位置。当匹配到登录请求时,立刻对验 证码进行校验,成功则放行,失败则提前结束整个验证请求。

说到Spring Security的过滤器,我们先回顾一下前面使用过的配置。

  1. @Override
  2. protected void configure(HttpSecurity http) throws Exception {
  3. http.authorizeRequests()
  4. .antMatchers("/admin/api/**").hasRole("ADMIN")
  5. .antMatchers("/user/api/**").hasRole("USER")
  6. .antMatchers("/app/api/**").permitAll()
  7. .anyRequest().authenticated()
  8. .and()
  9. .csrf().disable()
  10. .formLogin()
  11. .and()
  12. .sessionManagement()
  13. .maximumSessions(1);
  14. }

HttpSecurity实际上就是在配置Spring Security的过滤器链,诸如CSRF、CORS、表单登录等,每个 配置器对应一个过滤器。我们可以通过 HttpSecurity 配置过滤器的行为,甚至可以像CRSF一样直接关 闭过滤器。例如,SessionM anagement。

  1. public SessionManagementConfigurer<HttpSecurity> sessionManagement() throws Exception{
  2. return (SessionManagementConfigurer) this.getOrApply(new SessionManagementConfigurer());
  3. }

Spring Security通过SessionManagementConfigurer 来配置SessionManagement的行为。与 SessionManagementConfigurer类似的配置器还有 CorsConfigurer、RememberMeConfigurer 等,它们都实现了Security Configurer的标准接口。

  1. public interface SecurityConfigurer<O, B extends SecurityBuilder<O>> {
  2. //各个配置器的初始化方法
  3. void init(B var1) throws Exception;
  4. //各个配置器被统一调用的配置方法
  5. void configure(B var1) throws Exception;
  6. }

SessionManagementConfigurer是在configure方法中将最终的SessionManagementFilter插入过滤器链来实现会话管理的。

  1. public void configure(H http) {
  2. SecurityContextRepository securityContextRepository = (SecurityContextRepository)http.getSharedObject(SecurityContextRepository.class);
  3. //初始化SessionManagementFilter
  4. SessionManagementFilter sessionManagementFilter = new SessionManagementFilter(securityContextRepository, this.getSessionAuthenticationStrategy(http));
  5. if (this.sessionAuthenticationErrorUrl != null) {
  6. sessionManagementFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(this.sessionAuthenticationErrorUrl));
  7. }
  8. InvalidSessionStrategy strategy = this.getInvalidSessionStrategy();
  9. if (strategy != null) {
  10. sessionManagementFilter.setInvalidSessionStrategy(strategy);
  11. }
  12. AuthenticationFailureHandler failureHandler = this.getSessionAuthenticationFailureHandler();
  13. if (failureHandler != null) {
  14. sessionManagementFilter.setAuthenticationFailureHandler(failureHandler);
  15. }
  16. AuthenticationTrustResolver trustResolver = (AuthenticationTrustResolver)http.getSharedObject(AuthenticationTrustResolver.class);
  17. if (trustResolver != null) {
  18. sessionManagementFilter.setTrustResolver(trustResolver);
  19. }
  20. sessionManagementFilter = (SessionManagementFilter)this.postProcess(sessionManagementFilter);
  21. //将SessionManagementFilter添加到过滤器上
  22. http.addFilter(sessionManagementFilter);
  23. if (this.isConcurrentSessionControlEnabled()) {
  24. ConcurrentSessionFilter concurrentSessionFilter = this.createConcurrencyFilter(http);
  25. concurrentSessionFilter = (ConcurrentSessionFilter)this.postProcess(concurrentSessionFilter);
  26. http.addFilter(concurrentSessionFilter);
  27. }
  28. }

除Spring Security提供的过滤器外,我们还可以添加自己的过滤器以实现更多的安全功能,这些都 可以在HttpSecurity中实现。

  1. //将自定义过滤器添加到指定过滤器之后
  2. public HttpSecurity addFilterAfter(Filter filter, Class<? extends Filter> afterFilter) {
  3. this.comparator.registerAfter(filter.getClass(), afterFilter);
  4. return this.addFilterAfter(filter);
  5. }
  6. //将自定义过滤器添加到指定过滤器之前
  7. public HttpSecurity addFilterBefore(Filter filter, Class<? extends Filter> beforeFilter) {
  8. this.comparator.registerBefore(filter.getClass(), beforeFilter);
  9. return this.addFilter(filter);
  10. }
  11. //添加一个过滤器,但必须是Spring Security自身提供的过滤器实例或继承过滤器
  12. //详见FilterComparator类
  13. public HttpSecurity addFilter(Filter filter) {
  14. Class<? extends Filter> filterClass = filter.getClass();
  15. if (!this.comparator.isRegistered(filterClass)) {
  16. throw new IllegalArgumentException("The Filter class" + filterClass.getName() + " does not have a registered order and cannot be added without a specified order. Consider using addFilterBefore or addFilterAfter instead.");
  17. } else {
  18. this.filters.add(filter);
  19. return this;
  20. }
  21. }
  22. //添加一个自定义过滤器在指定过滤器位置
  23. public HttpSecurity addFilterAt(Filter filter, Class<? extends Filter> atFilter) {
  24. this.comparator.registerAt(filter.getClass(), atFilter);
  25. return this.addFilter(filter);
  26. }

4.1.2 图形验证码过滤器

毋庸置疑,要想实现图形验证码校验功能,首先应当有一个用于获取图形验证码的 API。绘制图形验证码的方法有很多,使用开源的验证码组件即可,例如kaptcha。

  1. <dependency>
  2. <groupId>com.github.penggle</groupId>
  3. <artifactId>kaptcha</artifactId>
  4. <version>2.3.2</version>
  5. </dependency>

kaptcha是一个很小的工具,使用方法极其简单,不再赘述。
首先配置一个kaptcha实例。

  1. @Bean
  2. public Producer captcha() {
  3. //配置图形验证码的基本参数
  4. Properties properties = new Properties();
  5. // 图片宽度
  6. properties.setProperty("kaptcha.image.width", "150");
  7. // 图片高
  8. properties.setProperty("kaptcha.image.height", "40");
  9. //字符集
  10. properties.setProperty("kaptcha.textproducer.char.string", "0123456789");
  11. // 验证码长度
  12. properties.setProperty("kaptcha.textproducer.char.length", "4");
  13. //图片边框
  14. properties.setProperty("kaptcha.border", "yes");
  15. // 边框颜色
  16. properties.setProperty("kaptcha.border.color", "105,179,90");
  17. // 字体颜色
  18. properties.setProperty("kaptcha.textproducer.font.color", "red");
  19. // 字体大小
  20. properties.setProperty("kaptcha.textproducer.font.size", "30");
  21. // session key
  22. properties.setProperty("kaptcha.session.key", "code");
  23. // 字体
  24. properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
  25. Config config = new Config(properties);
  26. //使用默认的图形验证码实现,也可以自定义
  27. DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
  28. defaultKaptcha.setConfig(config);
  29. return defaultKaptcha;
  30. }

接着创建一个CaptchaController,用于获取图形验证码。

  1. @Controller
  2. public class KaptchaController {
  3. @Autowired
  4. private Producer captchaProducer;
  5. @GetMapping("/captcha.jpg")
  6. public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
  7. //设置内容类型
  8. response.setContentType("image/jpeg");
  9. //创建验证码文本
  10. String capText = captchaProducer.createText();
  11. //将验证码文本设置到session
  12. request.getSession().setAttribute("captcha", capText);
  13. //创建验证码图片
  14. BufferedImage bi = captchaProducer.createImage(capText);
  15. //获取响应输出流
  16. ServletOutputStream out = response.getOutputStream();
  17. ImageIO.write(bi, "jpg", out);
  18. //推送并关闭响应输出流
  19. try {
  20. out.flush();
  21. } finally {
  22. out.close();
  23. }
  24. }
  25. }

当用户访问/captcha.jpg时,即可得到一张携带验证码的图片,验证码文本则被存放到session中, 用于后续的校验。
有了图形验证码的API之后,就可以自定义验证码校验过滤器了。虽然Spring Security的过滤器链 对过滤器没有特殊要求,只要继承了Filter即可,但是在Spring 体系中,推荐使用OncePerRequestFilter来实现,它可以确保一次请求只会通过一次该过滤器(Filter实际上并不能保证这一点)。

  1. /**
  2. * 专门用于校验验证码的过滤器
  3. */
  4. public class VerificationCodeFilter extends OncePerRequestFilter {
  5. private AuthenticationFailureHandler authenticationFailureHandler = new MyAuthenticationFailureHandler();
  6. @Override
  7. protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
  8. //非登录请求不校验验证码
  9. if (!"/auth/form".equals(httpServletRequest.getRequestURI())) {
  10. filterChain.doFilter(httpServletRequest, httpServletResponse);
  11. } else {
  12. try {
  13. verificationCode(httpServletRequest);
  14. filterChain.doFilter(httpServletRequest, httpServletResponse);
  15. } catch (VerificationCodeException e) {
  16. authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
  17. }
  18. }
  19. }
  20. public void verificationCode(HttpServletRequest httpServletRequest) throws VerificationCodeException {
  21. String requestCode = httpServletRequest.getParameter("captcha");
  22. HttpSession session = httpServletRequest.getSession();
  23. String savedCode = (String) session.getAttribute("captcha");
  24. if (!StringUtils.isEmpty(savedCode)) {
  25. //随手清除验证码,无论是失败,还是成功。客户端应在登录失败时刷新验证码
  26. session.removeAttribute("captcha");
  27. }
  28. //校验不通过,抛出异常
  29. if (StringUtils.isEmpty(requestCode) || StringUtils.isEmpty(savedCode) || !requestCode.equals(savedCode)) {
  30. throw new VerificationCodeException();
  31. }
  32. }
  33. }

总体来说,验证码仅仅核对session中保存的验证码与用户提交的验证码是否一致,逻辑并不复杂,只需将该过滤器添加到Spring Security的过滤器链中即可生效。

  1. @Override
  2. protected void configure(HttpSecurity http) throws Exception {
  3. http.authorizeRequests()
  4. .antMatchers("/admin/api/**").hasRole("ADMIN")
  5. .antMatchers("/user/api/**").hasRole("USER")
  6. //开放captcha.jpg的访问权限
  7. .antMatchers("/app/api/**", "/captcha.jpg").permitAll()
  8. .anyRequest().authenticated()
  9. .and()
  10. .csrf().disable()
  11. .formLogin()
  12. .loginPage("/myLogin.html")
  13. .loginProcessingUrl("/auth/form").permitAll()
  14. .failureHandler(new MyAuthenticationFailureHandler());
  15. //将过滤器添加到UsernamePasswordAuthenticationFilter之前
  16. http.addFilterBefore(new VerificationCodeFilter(), UsernamePasswordAuthenticationFilter.class);
  17. }

为了体验效果,下面修改自定义表单登录页。

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html:charset=utf-8"/>
  5. <title>登陆</title>
  6. <style>
  7. /*some style省略*/
  8. </style>
  9. </head>
  10. <body>
  11. <div class="login">
  12. <h2>Acced Form</h2>
  13. <div class="login-top">
  14. <h1>LOGIN FORM</h1>
  15. <form action="myLogin.html" method="post">
  16. <input type="text" name="username" placeholder="username"/>
  17. <input type="password" name="password" placeholder="password"/>
  18. <!-- 新增图形验证码输入框-->
  19. <input type="text" name="captcha" placeholder="captcha"/>
  20. <!-- 图片指向图形验证码API-->
  21. <img src="/captcha.jpg" alt="captcha" height="50px" width="150px" style="margin-left: 20px;">
  22. <div class="forgot">
  23. <a href="#">forgot Password</a>
  24. <input type="submit" value="Login">
  25. </div>
  26. </form>
  27. </div>
  28. <div class="login-botton">
  29. <h3>New User &nbsp;<a href="#">Register &nbsp Here</a></h3>
  30. </div>
  31. </div>
  32. </body>
  33. </html>

重启服务,访问任意一个受保护的资源即可看到带验证码的登录页面,如图4-1所示。
当正确输入验证码时,可以正常访问对应资源。只要输入的验证码有误,就会返回一个401页面, 如图4-2所示。

至此,验证码登录功能就粗略实现了,而定制验证码的尺寸、验证码的失效属性、配置验证码的
字符取值范围等,可以在此基础上集成。

第7章 密码加密

密码安全是互联网安全的一个缩影,我们在享受互联网服务的同时,也应当对它投入更多的关注。

7.1 密码安全的重要性

2011年12月,国内某开发者社区网站被黑客“拖库”,600多万个密码明文存储的用户账号被公开, 大量用户直接面临数据隐私泄露和数据安全的双重威胁。
这次事件为我们敲响了警钟,一旦发生“拖库”,如何尽可能地减少用户的损失,在每一个系统中都不应被忽略。从开发者的角度而言,可以落实在如何安全存储用户密码上。

为什么要安全存储用户密码呢?当被“拖库”时,当前系统的所有数据就成为既定损失,如果用户的密码同时被泄露,且未做加密,那么即便及时修复了“拖库”的问题,后续也可能会导致扩散性损 失。因为黑客手里还握着大量的用户密码,安全威胁随时都在,这时能做的只能是紧急升级系统,强制所有用户验证手机号码或邮箱,并重置密码方能再次进入,这显然很被动。如果在系统开发之初就有安全存储用户密码的意识,则能有效防止这种情况。

7.2 密码加密的演进

安全存储用户密码很多时候都是使用加密的方式来进行的。提到加密,诸如MD5、SHA等摘要算法通常会第一时间浮现在我们脑海里,尽管它们并非真正的加密(不可逆)。例如,在密码加密这个场景下,对用户密码进行 MD5运算后再存储就是一种看起来可行的思路,只要在每次登录验证时,对用户提交的密码进行同样的MD5运算,然后与数据库中存储的值进行对比即可。

事实上,尽管摘要算法无法通过逆运算获得原文,但由于摘要值有限(MD5算法最多只能表示36的16次方个摘要值),而原文无限,所以一定存在两个甚至更多个不同数据通过运算得到同一摘要值的情况,即存在被“碰撞”的可能。

除“碰撞”外,最直接的破解方式是构建反查表。相同串(密码)经过 MD5运算后一定会得到同一个值,于是有些人便制作了这样一张表,如表7-1所示。

@TODO

7.3 Spring Security的密码加密机制

Spring Security内置了密码加密机制,只需使用一个PasswordEncoder接口即可。

  1. public interface PasswordEncoder {
  2. String encode(CharSequence var1);
  3. boolean matches(CharSequence var1, String var2);
  4. }

PasswordEncoder接口定义了encode和matches两个方法,当用数据库存储用户密码时,加密过程用encode方法,matches方法用于判断用户登录时输入的密码是否正确。

此外,Spring Security还内置了几种常用的PasswordEncoder接口,例如,StandardPasswordEncoder中的常规摘要算法(SHA-256等)、BCryptPasswordEncoder加密,以及类似BCrypt的慢散列加密Pbkdf2PasswordEncoder等,官方推荐使用BCryptPasswordEncoder。

下面我们就尝试在系统中接入BCrypt这种密码加密方式。由于BCrypt加密后的密文长度超过50, 所以在我们的表结构中,如果用户密码字段过短将会导致出错,因此应首先检查并确保密码字段长度 已经扩充到60以上。接着用一个BCrypt密文来实验,可以使用前面示例的BCrypt密文,它的原文是“ blurooo”,我们可以修改表中的某个用户密码为该密文,如图7-2所示。

数据方面已经准备完毕,Spring Security方面的配置其实非常简单:

  1. @Bean
  2. PasswordEncoder passwordEncoder() {
  3. PasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder(12);
  4. return bcryptPasswordEncoder;
  5. }

在声明一个PasswordEncoder的bean之后,Spring Security 会自动应用。重启服务,发现user这个用户已经无法通过密码123来登录了。实际上需要什么密码没有人知道,但admin可以使用“blurooo”来登录,验证了我们的配置是有效的。
到这一步并没有完成密码加密的完整接入,因为新用户“写库”时密码还是明文,需要做一些调整。

  1. @Autowired
  2. private PasswordEncoder passwordEncoder;
  3. @PostMapping("/users")
  4. public User create(User user){
  5. //加密之后重新设置
  6. user.setPassword(passwordEncoder.encode(user.getPassword()));
  7. ...
  8. }

通常情况下,在新系统中使用BCrypt加密不需要考量太多,但老系统由于存在大量旧数据,草率接入会导致老用户无法登录,这种情况该怎么解决呢?很简单,我们自己实现一个PasswordEncoder并 继承BCryptPasswordEncoder即可。

  1. @Component
  2. public class MyPasswordEncoder extends BCryptPasswordEncoder {
  3. //BCrypt密文的正则表达式
  4. private static Pattern BCRYPT_PATTERN = Pattern.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");
  5. @Override
  6. public boolean matches(CharSequence rawPassword, String encodedPassword) {
  7. //如果密码不是BCrypt密文
  8. if (!BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
  9. ...
  10. }
  11. return super.matches(rawPassword, encodedPassword);
  12. }
  13. }

在这个PasswordEncoder中,只有当密码不是BCrypt密文时,才启用自定义的匹配逻辑,其余还是 沿用原来的方案,即可轻松达到兼容的目的。
再进一步,如果我们不仅想要兼容,还想将不安全的旧密码无缝修改成BCrypt密文,该如何操作呢?这是个很好的问题。如果旧密码都是未经任何加密的明文,也许“跑库”修改是非常好的一种选 择,但并非所有系统都有这么理想的状态。假如旧密码都是被散列加密过的,那么可以用下面两种方 法解决这个问题:
◎ 使用增量更新的方法。当用户输入的密码正确时,判断数据库中的密码是否为BCrypt密文,如 果不是,则尝试使用用户输入的密码重新生成BCrypt密文并写回数据库。
◎ 以旧的加密方案作为基础接入BCrypt加密。例如,旧的方案是MD5加密,即数据库中的所有 密码都是 MD5形式的密码,那么直接把这些密码当作明文,先“跑库”生成 BCrypt密文,再使用 encode和matches两个方法在执行BCrypt加密之前都先用MD5运算一遍即可。
密码安全对系统来说,从来都是一个不小的挑战,即便实现了安全存储,仍然有很多的途径泄露用户密码。用户密码在提交到系统之前就被盗取的案例数不胜数,如挂木马或是抓包等。很多时候,用户往往无法准确识别陷阱,而我们能做的,就是尽可能地做好安全措施。例如,采用HTTPS安全信道,甚至是开发银行级别的安全控件,帮助用户检测系统环境是否正常。