第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应用的核心依赖。
查看Pom文件
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.4</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>spring-demo</artifactId><version>0.0.1-SNAPSHOT</version><name>spring-demo</name><description>spring-demo</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
下面打开程序的入口类SpringDemoApplication,声明一个hello路由。
@RestController@SpringBootApplicationpublic class SpringDemoApplication {@GetMapping("/")public String hello() {return "hello,spring security";}public static void main(String[] args) {SpringApplication.run(SpringDemoApplication.class, args);}}
启动程序,输入http://localhost:8080 可以看到登陆框
在引入Spring Security项目之后,虽然没有进行任何相关的配置或编码,但Spring Security有一个默认的运行状态,要求在经过HTTP基本认证后才能访问对应的URL资源,其默认使用的用户名为user,密码则是动态生成并打印到控制台的一串随机码。翻看控制台的打印信息,可以看到如图所示的输出。
4b6fe046-dd65-4cb5-acf2-edc3a4e84eb6
输入用户名和密码后,单击“登录”按钮即可成功访问hello页面,如图所示。
当然,右HTTP基本认证中,用户名和密码都是可以配置的,最常见的就是在resources下的配置文件中修改。
打开application.properties,输入以下配置信息:
server.port=18080spring.security.user.name=adminspring.security.user.password=admin
重新启动程序,发现控制台不再打印默认密码串了,此时使用我们自定义的用户名和密码即可登录。
事实上,绝大部分Web应用都不会选择HTTP基本认证这种认证方式,除安全性差、无法携带cookie等因素外,灵活性不足也是它的一个主要缺点。通常大家更愿意选择表单认证,自己实现表单 登录页和验证逻辑,从而提高安全性。
我的页面返回的是错误
Whitelabel Error PageThis application has no explicit mapping for /error, so you are seeing this as a fallback.Thu Sep 23 10:50:53 CST 2021There was an unexpected error (type=Not Found, status=404).原因是启动类上没有添加注解:@RestControler
第2章 表单认证
2.1 默认表单认证
首先,新建一个configuration包用于存放通用配置;然后,新建一个WebSecurityConfig类,使其继承WebSecurityConfigurerAdapter
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {}
接着查看WebSecurityConfigurerAdapter类对configure(HttpSecurity http)的定义。
protected void configure(HttpSecurity http) throws Exception {this.logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");http.authorizeRequests((requests) -> {((AuthorizedUrl)requests.anyRequest()).authenticated();});http.formLogin();http.httpBasic();}
可以看到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方法。
@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/myLogin.html")//使登陆页不设限访问.permitAll().and().csrf().disable();}}
2.认识HttpSecurity
HttpSecurity实际上对应了=Spring Security命名空间配置方式中XML文件内的标签,允许我们为特 定的HTTP请求配置安全策略。
在XML文件中,声明大量配置早已司空见惯;但在Java配置中,按照传统的方式,我们需要这样来调用。
@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry urlRegistry = http.authorizeRequests();ExpressionUrlAuthorizationConfigurer.AuthorizedUrl authorizedUrl = (ExpressionUrlAuthorizationConfigurer.AuthorizedUrl) urlRegistry.anyRequest();authorizedUrl.authenticated();//moreFormLoginConfigurer<HttpSecurity> formLoginConfigurer = http.formLogin();formLoginConfigurer.loginPage("/myLogin.html");formLoginConfigurer.permitAll();//mort}}
可以想象出这是多么烦琐且令人痛苦的一件事。HttpSecurity首先被设计为链式调用,在执行每个方法后,都会返回一个预期的上下文,便于连续调用。我们不需要关心每个方法究竟返回了什么、如何进行下一个配置等细节。
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页面,如图所示。
3.编写表单登录页
表单登录页的代码如下所示。
<!DOCTYPE html><html lang="en"><head><meta http-equiv="Content-Type" content="text/html:charset=utf-8"/><title>登陆</title><style>/*some style*/</style></head><body><div class="login"><h2>Acced Form</h2><div class="login-top"><h1>LOGIN FORM</h1><form action="myLogin.html" method="post"><input type="text" name="username" placeholder="username"/><input type="password" name="password" placeholder="password"/><div class="forgot"><a href="#">forgot Password</a><input type="submit" value="Login"></div></form></div><div class="login-botton"><h3>New User <a href="#">Register   Here</a></h3></div></div></body></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在表单定制里提供了相应的支持。
@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/myLogin.html").loginProcessingUrl("/login")//使登陆页不设限访问.permitAll().and().csrf().disable();}}
此时,有些读者可能会有疑问,因为按照惯例,在发送登录请求并认证成功之后,页面会跳转回原访问页。在某些系统中的确是跳转回原访问页的,但在部分前后端完全分离、仅靠JSON完成所有交互的系统中,一般会在登录时返回一段JSON数据,告知前端成功登录成功与否,由前端决定如何处理后续逻辑,而非由服务器主动执行页面跳转。这在Spring Security中同样可以实现。
@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/myLogin.html")//指定处理登陆请求的路径.loginProcessingUrl("/login")//指定处理登陆成功时的处理逻辑.successHandler(new AuthenticationSuccessHandler() {@Overridepublic void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {httpServletResponse.setContentType("application/json;charset=UTF-8");PrintWriter out = httpServletResponse.getWriter();out.write("{\"error_code\":\"0\",\"meeeage\":\"欢迎登陆系统\"}");}})//指定登陆失败时的处理逻辑.failureHandler(new AuthenticationFailureHandler() {@Overridepublic void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {httpServletResponse.setContentType("application/json;charset=UTF-8");httpServletResponse.setStatus(401);PrintWriter out = httpServletResponse.getWriter();//输出失败的原因out.write("{\"error_code\":\"401\",\"name\":\"" + e.getClass() + "\",\"message\":\"" + e.getMessage() + "\"}");}}).and().csrf().disable();}}
第3章 认证与授权
在第2章中,我们沿用了Spring Security默认的安全机制:仅有一个用户,仅有一种角色。在实 际开发中,这自然是无法满足需求的。本章将更加深入地对Spring Security迚行配置,且初步使用授权机制。
3.1 默认数据库模型的认证与授权
3.1.1 资源准备
首先,在controller包下新建三个控制器,如图3-1所示。
其次,分别建立一些测试路由。
@RestController@RequestMapping("/admin/api")public class AdminController {@GetMapping("hello")public String hello() {return "hello,admin";}}@RestController@RequestMapping("/app/api")public class AppController {@GetMapping("hello")public String hello() {return "hello,app";}}@RestController@RequestMapping("/user/api")public class UserController {@GetMapping("hello")public String hello() {return "hello,user";}}
假设在/admin/api/下的内容是系统后台管理相关的 API,在/app/api 下的内容是面向客户端公开访 问的API,在/user/api/下的内容是用户操作自身数据相关的API;显然,/admin/api必须拥有管理员权限 才能进行操作,而/user/ap i必须在用户登录后才能进行操作。
3.1.2 资源授权的配置
为了能正常访问前面的路由,我们需要进一步地配置Spring Security。
@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin/api/**").hasRole("ADMIN").antMatchers("/user/api/**").hasRole("USER").antMatchers("/app/api/**").permitAll().anyRequest().authenticated().and().formLogin();}}
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
�即可。
@Beanpublic UserDetailsService userDetailsService() {InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();manager.createUser(User.withUsername("user").password("123").roles("USER").build());manager.createUser(User.withUsername("admin").password("123").roles("USER", "ADMIN").build());return manager;}
为其添加一个@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两个必要依赖。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency>
接着在application.properties中配置数据库连接参数。
spring.datasource.url=jdbc:mysql://39.100.127.235:13306/springDemo?userUnicode=true&characterEncoding=utf-8&userSSL=falsespring.datasource.username=rootspring.datasource.password=root
这里连接的数据库名为springDemo(不配置driverClassName也不会出现问题,因为Spring Boot会自动根据URL去推断)。用户名、密码分别为root和123456,读者可根据实际情况,自行修改。
前面介绍过,JdbcUserDetailsManager设定了一个默认的数据库模型,Spring Security将该模型定义在/org/springframework/security/core/userdetails/jdbc/users.ddl内。
create table users(username varchar(50) not null primary key,password varchar(500) not null,enabled boolean not null);create table authorities(username varchar(50) not null,authority varchar(50) not null,constraint fk_authorities_users foreign key (username) references users (username));create unique index ix_auth_username on authorities (username, authority);
JdbcUserDetailsManager需要两个表,其中users表用来存放用户名、密码和是否可用三个信息, authorities表用来存放用户名及其权限的对应关系。
2.编码实现
下面构建一个JdbcUserDetailsManager实例,让Spring Security使用数据库来管理用户。
import org.apache.tomcat.jdbc.pool.DataSource;@Autowiredprivate DataSource dataSource;@Override@Beanpublic UserDetailsService userDetailsService() {JdbcUserDetailsManager manager = new JdbcUserDetailsManager();manager.setDataSource(dataSource);manager.createUser(User.withUsername("user").password("123").roles("USER").build());manager.createUser(User.withUsername("admin").password("123").roles("USER", "ADMIN").build());return manager;}
JdbcUserDetailsManager与InMemoryUserDetailsManager在用法上没有太大区别,只是多了设置DataSource的环节。Spring Security 通过 DataSource 执行设定好的命令。例如,此处的createUser函数实际上就是执行了下面的SQL语句。
INSERT INTO users(username,password,enabled) values(?,?,?)
查看JdbcUserDetailsManager的源代码可以看到更多定义好的SQL语句,诸如deleteUserSql、updateUserSql等,这些都是JdbcUserDetailsManager与数据库实际交互的形式。当然, JdbcUserDetailsManager也允许我们在特殊情况下自定义这些SQL语句,如有必要,调用对应的 setXxxSql方法即可。
现在重启服务,看看在数据库中Spring Security生成了哪些数据。
authorities 表的authority 字段存放的是前面设定的角色,只是会被添上“ROLE_”前缀。下面尝试
通过SQL命令创建一个测试账号。
INSERT INTO users values(“test”,“123”,true);INSERT INTO authorities values("test","ROLE_USER");
清空缓存并使用测试账号访问系统,发现可以访问user路由,但不能访问admin路由,与预期的行 为一致。
到目前为止,一切都工作得很好,但是只要我们重启服务,应用就会报错。这是因为users表在创建语句时,username字段为主键,主键是唯一不重复的,但重启服务后会再次创建admin和user,导致数据库报错(在内存数据源上不会出现这种问题,因为重启服务后会清空username字段中的内容)。 所以如果需要在服务启动时便生成部分用户,那么建议先判断用户名是否存在。
@Beanpublic UserDetailsService userDetailsService() {JdbcUserDetailsManager manager = new JdbcUserDetailsManager();manager.setDataSource(dataSource);if (!manager.userExists("user")) {manager.createUser(User.withUsername("user").password("123").roles("USER").build());}if (!manager.userExists("admin")) {manager.createUser(User.withUsername("admin").password("123").roles("USER", "ADMIN").build());}return manager;}
在2.2节的自定义表单登录页中,WebSecurityConfigurer Adapter定义了三个configure。
protected void configure(AuthenticationManagerBuilder auth) throws Exception {this.disableLocalConfigureAuthenticationBldr = true;}public void configure(WebSecurity web) throws Exception {}protected void configure(HttpSecurity http) throws Exception {this.logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");http.authorizeRequests((requests) -> {((AuthorizedUrl)requests.anyRequest()).authenticated();});http.formLogin();http.httpBasic();}
我们只用到了一个参数,用来接收HttpSecurity对象的配置方法。另外两个参数也有各自的用途,其中,AuthenticationManagerBuilder的configure同样允许我们配置认证用户。
@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin/api/**").hasRole("ADMIN").antMatchers("/user/api/**").hasRole("USER").antMatchers("/app/api/**").permitAll().anyRequest().authenticated().and().formLogin();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password("123").roles("user").and().withUser("admin").password("123").roles("admin");}
使用方法大同小异,这里不再赘述。
当使用Spring Security默认数据库模型应对各种用户系统时,难免灵活性欠佳。尤其是在对现有的 系统做Spring Security嵌入时,原本的用户数据已经固定,为了适配Spring Security而在数据库层面进行 修改显然得不偿失。强大而灵活的Spring Security对这方面进行了改进。
错误说明-java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id “null”
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
Spring security 5.0中新增了多种加密方式,也改变了默认的密码格式,不再允许使用明文。所以要进行相应的加密处理。
WebSecurityConfig.java文件登陆验证时@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//读取时使用密码加密auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());}存储加密时:新增用户时加密@Beanpublic UserDetailsService userDetailsService() {JdbcUserDetailsManager manager = new JdbcUserDetailsManager();manager.setDataSource(dataSource);if (!manager.userExists("user")) {manager.createUser(User.withUsername("user").password(passwordEncoder.encode("123")).roles("USER").build());}if (!manager.userExists("admin")) {manager.createUser(User.withUsername("admin").password(passwordEncoder.encode("123")).roles("USER", "ADMIN").build());}return manager;}}
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会根据这些信息判定验证是否成功。
public interface UserDetails extends Serializable {Collection<? extends GrantedAuthority> getAuthorities();String getPassword();String getUsername();boolean isAccountNonExpired();boolean isAccountNonLocked();boolean isCredentialsNonExpired();boolean isEnabled();}
也就是说,不管数据库结构如何变化,只要能构造一个UserDetails即可,下面就来实现这个过程。
1.数据库准备
设计一个自定义的数据库结构。
create table users(id bigint(20) not null auto_increment,username varchar(50) not null,password varchar(64) not null,enabled tinyint(4) not null default '1' comment '用户是否可用',roles text CHARACTER SET utf8 comment '用户角色,多个角色之间用逗号隔开',primary key (id),KEY username (username));
我们把用户信息和角色放在同一张表中,不再是Spring Security默认的分开形式。roles字段设定为 text 类型,多个角色之间用逗号隔开。建议在username字段上建立索引,以提高搜索速度。
插入两条数据
insert into users (username, password, roles) values ('admin','123','ROLE_ADMIN,ROLE_USER');insert into users (username, password, roles) values ('user','123','ROLE_USER');
2.编码实现
当数据库结构和数据准备完毕时,即可编写对应的User实体。
�
public class User {private Long id;private String username;private String password;private String roles;private boolean enabled;//get and set}
让User实体继承UserDetails
public class User implements UserDetails {private Long id;private String username;private String password;private String roles;private boolean enabled;private List<GrantedAuthority> authorities;@Overridepublic boolean isAccountNonExpired() {return true;}@Overridepublic boolean isAccountNonLocked() {return true;}@Overridepublic boolean isCredentialsNonExpired() {return true;}@Overridepublic Collection<? extends GrantedAuthority> getAuthorities() {return this.authorities;}}
实现UserDetails定义的几个方法:
◎ isAccountNonExpired、isAccountNonLocked 和 isCredentialsNonExpired 暂且用不到,统一返回 true,否则Spring Security会认为账号异常。
◎ isEnabled对应enable字段,将其代入即可。
◎ getAuthorities方法本身对应的是roles字段,但由于结构不一致,所以此处新建一个,并在后续 进行填充。
3.2.2 实现UserDetailsService
当准备好UserDetails之后,使用数据库持久层框架读取数据并填充对象。首先引入MyBatis。
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.1</version></dependency>
前面在配置文件中曾写过数据库相关的配置,这里沿用即可。
�接下来在入口类中用@MapperScan指定MyBatis要扫描的映射文件目录。
@MapperScan("com.example.springdemo.mapper")@SpringBootApplicationpublic class SpringDemoApplication {public static void main(String[] args) {SpringApplication.run(SpringDemoApplication.class, args);}}
编写对应的Mapper
@Componentpublic interface UserMapper {@Select("Select * FROM users WHERE username=#{username}")User findByUserName(@Param("username") String username);}
与MyBatis相关的内容不再赘述,没有接触过且感兴趣的读者可以自行学习相关知识,这里仅提 供一个通过用户名查找用户的方法。
2.编码实现
当数据持久层准备完成后,我们开始编写UserDetailsService。
@Servicepublic class MyUserDetailsService implements UserDetailsService {@Autowiredprivate UserMapper userMapper;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {//从数据库尝试读取该用户User user = userMapper.findByUserName(username);//用户不存在,抛出异常if (user == null) {throw new UsernameNotFoundException("用户不存在");}//将数据库形式的roles解析为UserDEtails的权限集//AuthorityUtils.commaSeparatedStringToAuthorityList是Spring Security提供的,该方法用于将逗号隔开的权限集字符串切割成可用权限对象列表//当前也可以自己实现,如用分号来隔开等,参考generateAuthoritiesuser.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()));return user;}private List<GrantedAuthority> generateAuthorities(String roles) {List<GrantedAuthority> authorities = new ArrayList<>();String[] roleArray = roles.split(";");if (roles != null && "".equals(roles)) {for (String role : roleArray) {authorities.add(new SimpleGrantedAuthority(role));}}return authorities;}}
其中,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的过滤器,我们先回顾一下前面使用过的配置。
@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin/api/**").hasRole("ADMIN").antMatchers("/user/api/**").hasRole("USER").antMatchers("/app/api/**").permitAll().anyRequest().authenticated().and().csrf().disable().formLogin().and().sessionManagement().maximumSessions(1);}
HttpSecurity实际上就是在配置Spring Security的过滤器链,诸如CSRF、CORS、表单登录等,每个 配置器对应一个过滤器。我们可以通过 HttpSecurity 配置过滤器的行为,甚至可以像CRSF一样直接关 闭过滤器。例如,SessionM anagement。
public SessionManagementConfigurer<HttpSecurity> sessionManagement() throws Exception{return (SessionManagementConfigurer) this.getOrApply(new SessionManagementConfigurer());}
Spring Security通过SessionManagementConfigurer 来配置SessionManagement的行为。与 SessionManagementConfigurer类似的配置器还有 CorsConfigurer、RememberMeConfigurer 等,它们都实现了Security Configurer的标准接口。
public interface SecurityConfigurer<O, B extends SecurityBuilder<O>> {//各个配置器的初始化方法void init(B var1) throws Exception;//各个配置器被统一调用的配置方法void configure(B var1) throws Exception;}
SessionManagementConfigurer是在configure方法中将最终的SessionManagementFilter插入过滤器链来实现会话管理的。
public void configure(H http) {SecurityContextRepository securityContextRepository = (SecurityContextRepository)http.getSharedObject(SecurityContextRepository.class);//初始化SessionManagementFilterSessionManagementFilter sessionManagementFilter = new SessionManagementFilter(securityContextRepository, this.getSessionAuthenticationStrategy(http));if (this.sessionAuthenticationErrorUrl != null) {sessionManagementFilter.setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(this.sessionAuthenticationErrorUrl));}InvalidSessionStrategy strategy = this.getInvalidSessionStrategy();if (strategy != null) {sessionManagementFilter.setInvalidSessionStrategy(strategy);}AuthenticationFailureHandler failureHandler = this.getSessionAuthenticationFailureHandler();if (failureHandler != null) {sessionManagementFilter.setAuthenticationFailureHandler(failureHandler);}AuthenticationTrustResolver trustResolver = (AuthenticationTrustResolver)http.getSharedObject(AuthenticationTrustResolver.class);if (trustResolver != null) {sessionManagementFilter.setTrustResolver(trustResolver);}sessionManagementFilter = (SessionManagementFilter)this.postProcess(sessionManagementFilter);//将SessionManagementFilter添加到过滤器上http.addFilter(sessionManagementFilter);if (this.isConcurrentSessionControlEnabled()) {ConcurrentSessionFilter concurrentSessionFilter = this.createConcurrencyFilter(http);concurrentSessionFilter = (ConcurrentSessionFilter)this.postProcess(concurrentSessionFilter);http.addFilter(concurrentSessionFilter);}}
除Spring Security提供的过滤器外,我们还可以添加自己的过滤器以实现更多的安全功能,这些都 可以在HttpSecurity中实现。
//将自定义过滤器添加到指定过滤器之后public HttpSecurity addFilterAfter(Filter filter, Class<? extends Filter> afterFilter) {this.comparator.registerAfter(filter.getClass(), afterFilter);return this.addFilterAfter(filter);}//将自定义过滤器添加到指定过滤器之前public HttpSecurity addFilterBefore(Filter filter, Class<? extends Filter> beforeFilter) {this.comparator.registerBefore(filter.getClass(), beforeFilter);return this.addFilter(filter);}//添加一个过滤器,但必须是Spring Security自身提供的过滤器实例或继承过滤器//详见FilterComparator类public HttpSecurity addFilter(Filter filter) {Class<? extends Filter> filterClass = filter.getClass();if (!this.comparator.isRegistered(filterClass)) {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.");} else {this.filters.add(filter);return this;}}//添加一个自定义过滤器在指定过滤器位置public HttpSecurity addFilterAt(Filter filter, Class<? extends Filter> atFilter) {this.comparator.registerAt(filter.getClass(), atFilter);return this.addFilter(filter);}
4.1.2 图形验证码过滤器
毋庸置疑,要想实现图形验证码校验功能,首先应当有一个用于获取图形验证码的 API。绘制图形验证码的方法有很多,使用开源的验证码组件即可,例如kaptcha。
<dependency><groupId>com.github.penggle</groupId><artifactId>kaptcha</artifactId><version>2.3.2</version></dependency>
kaptcha是一个很小的工具,使用方法极其简单,不再赘述。
首先配置一个kaptcha实例。
@Beanpublic Producer captcha() {//配置图形验证码的基本参数Properties properties = new Properties();// 图片宽度properties.setProperty("kaptcha.image.width", "150");// 图片高properties.setProperty("kaptcha.image.height", "40");//字符集properties.setProperty("kaptcha.textproducer.char.string", "0123456789");// 验证码长度properties.setProperty("kaptcha.textproducer.char.length", "4");//图片边框properties.setProperty("kaptcha.border", "yes");// 边框颜色properties.setProperty("kaptcha.border.color", "105,179,90");// 字体颜色properties.setProperty("kaptcha.textproducer.font.color", "red");// 字体大小properties.setProperty("kaptcha.textproducer.font.size", "30");// session keyproperties.setProperty("kaptcha.session.key", "code");// 字体properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");Config config = new Config(properties);//使用默认的图形验证码实现,也可以自定义DefaultKaptcha defaultKaptcha = new DefaultKaptcha();defaultKaptcha.setConfig(config);return defaultKaptcha;}
接着创建一个CaptchaController,用于获取图形验证码。
@Controllerpublic class KaptchaController {@Autowiredprivate Producer captchaProducer;@GetMapping("/captcha.jpg")public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {//设置内容类型response.setContentType("image/jpeg");//创建验证码文本String capText = captchaProducer.createText();//将验证码文本设置到sessionrequest.getSession().setAttribute("captcha", capText);//创建验证码图片BufferedImage bi = captchaProducer.createImage(capText);//获取响应输出流ServletOutputStream out = response.getOutputStream();ImageIO.write(bi, "jpg", out);//推送并关闭响应输出流try {out.flush();} finally {out.close();}}}
当用户访问/captcha.jpg时,即可得到一张携带验证码的图片,验证码文本则被存放到session中, 用于后续的校验。
有了图形验证码的API之后,就可以自定义验证码校验过滤器了。虽然Spring Security的过滤器链 对过滤器没有特殊要求,只要继承了Filter即可,但是在Spring 体系中,推荐使用OncePerRequestFilter来实现,它可以确保一次请求只会通过一次该过滤器(Filter实际上并不能保证这一点)。
/*** 专门用于校验验证码的过滤器*/public class VerificationCodeFilter extends OncePerRequestFilter {private AuthenticationFailureHandler authenticationFailureHandler = new MyAuthenticationFailureHandler();@Overrideprotected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {//非登录请求不校验验证码if (!"/auth/form".equals(httpServletRequest.getRequestURI())) {filterChain.doFilter(httpServletRequest, httpServletResponse);} else {try {verificationCode(httpServletRequest);filterChain.doFilter(httpServletRequest, httpServletResponse);} catch (VerificationCodeException e) {authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);}}}public void verificationCode(HttpServletRequest httpServletRequest) throws VerificationCodeException {String requestCode = httpServletRequest.getParameter("captcha");HttpSession session = httpServletRequest.getSession();String savedCode = (String) session.getAttribute("captcha");if (!StringUtils.isEmpty(savedCode)) {//随手清除验证码,无论是失败,还是成功。客户端应在登录失败时刷新验证码session.removeAttribute("captcha");}//校验不通过,抛出异常if (StringUtils.isEmpty(requestCode) || StringUtils.isEmpty(savedCode) || !requestCode.equals(savedCode)) {throw new VerificationCodeException();}}}
总体来说,验证码仅仅核对session中保存的验证码与用户提交的验证码是否一致,逻辑并不复杂,只需将该过滤器添加到Spring Security的过滤器链中即可生效。
@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin/api/**").hasRole("ADMIN").antMatchers("/user/api/**").hasRole("USER")//开放captcha.jpg的访问权限.antMatchers("/app/api/**", "/captcha.jpg").permitAll().anyRequest().authenticated().and().csrf().disable().formLogin().loginPage("/myLogin.html").loginProcessingUrl("/auth/form").permitAll().failureHandler(new MyAuthenticationFailureHandler());//将过滤器添加到UsernamePasswordAuthenticationFilter之前http.addFilterBefore(new VerificationCodeFilter(), UsernamePasswordAuthenticationFilter.class);}
为了体验效果,下面修改自定义表单登录页。
<!DOCTYPE html><html lang="en"><head><meta http-equiv="Content-Type" content="text/html:charset=utf-8"/><title>登陆</title><style>/*some style省略*/</style></head><body><div class="login"><h2>Acced Form</h2><div class="login-top"><h1>LOGIN FORM</h1><form action="myLogin.html" method="post"><input type="text" name="username" placeholder="username"/><input type="password" name="password" placeholder="password"/><!-- 新增图形验证码输入框--><input type="text" name="captcha" placeholder="captcha"/><!-- 图片指向图形验证码API--><img src="/captcha.jpg" alt="captcha" height="50px" width="150px" style="margin-left: 20px;"><div class="forgot"><a href="#">forgot Password</a><input type="submit" value="Login"></div></form></div><div class="login-botton"><h3>New User <a href="#">Register   Here</a></h3></div></div></body></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接口即可。
public interface PasswordEncoder {String encode(CharSequence var1);boolean matches(CharSequence var1, String var2);}
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方面的配置其实非常简单:
@BeanPasswordEncoder passwordEncoder() {PasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder(12);return bcryptPasswordEncoder;}
在声明一个PasswordEncoder的bean之后,Spring Security 会自动应用。重启服务,发现user这个用户已经无法通过密码123来登录了。实际上需要什么密码没有人知道,但admin可以使用“blurooo”来登录,验证了我们的配置是有效的。
到这一步并没有完成密码加密的完整接入,因为新用户“写库”时密码还是明文,需要做一些调整。
@Autowiredprivate PasswordEncoder passwordEncoder;@PostMapping("/users")public User create(User user){//加密之后重新设置user.setPassword(passwordEncoder.encode(user.getPassword()));...}
通常情况下,在新系统中使用BCrypt加密不需要考量太多,但老系统由于存在大量旧数据,草率接入会导致老用户无法登录,这种情况该怎么解决呢?很简单,我们自己实现一个PasswordEncoder并 继承BCryptPasswordEncoder即可。
@Componentpublic class MyPasswordEncoder extends BCryptPasswordEncoder {//BCrypt密文的正则表达式private static Pattern BCRYPT_PATTERN = Pattern.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");@Overridepublic boolean matches(CharSequence rawPassword, String encodedPassword) {//如果密码不是BCrypt密文if (!BCRYPT_PATTERN.matcher(encodedPassword).matches()) {...}return super.matches(rawPassword, encodedPassword);}}
在这个PasswordEncoder中,只有当密码不是BCrypt密文时,才启用自定义的匹配逻辑,其余还是 沿用原来的方案,即可轻松达到兼容的目的。
再进一步,如果我们不仅想要兼容,还想将不安全的旧密码无缝修改成BCrypt密文,该如何操作呢?这是个很好的问题。如果旧密码都是未经任何加密的明文,也许“跑库”修改是非常好的一种选 择,但并非所有系统都有这么理想的状态。假如旧密码都是被散列加密过的,那么可以用下面两种方 法解决这个问题:
◎ 使用增量更新的方法。当用户输入的密码正确时,判断数据库中的密码是否为BCrypt密文,如 果不是,则尝试使用用户输入的密码重新生成BCrypt密文并写回数据库。
◎ 以旧的加密方案作为基础接入BCrypt加密。例如,旧的方案是MD5加密,即数据库中的所有 密码都是 MD5形式的密码,那么直接把这些密码当作明文,先“跑库”生成 BCrypt密文,再使用 encode和matches两个方法在执行BCrypt加密之前都先用MD5运算一遍即可。
密码安全对系统来说,从来都是一个不小的挑战,即便实现了安全存储,仍然有很多的途径泄露用户密码。用户密码在提交到系统之前就被盗取的案例数不胜数,如挂木马或是抓包等。很多时候,用户往往无法准确识别陷阱,而我们能做的,就是尽可能地做好安全措施。例如,采用HTTPS安全信道,甚至是开发银行级别的安全控件,帮助用户检测系统环境是否正常。
