在 Web 开发中,安全一直是非常重要的一个方面。安全虽然属于应用的非功能性需求,但是应该在应用开发的初期就考虑进来。如果在应用开发的后期才考虑安全的问题,就可能陷入一个两难的境地:一方面,应用存在严重的安全漏洞,无法满足用户的要求,并可能造成用户的隐私数据被攻击者窃取;另一方面,应用的基本架构已经确定,要修复安全漏洞,可能需要对系统的架构做出比较重大的调整,因而需要更多的开发时间,影响应用的发布进程。因此,从应用开发的第一天就应该把安全相关的因素考虑进来,并在整个应用的开发过程中。市面上存在比较有名的:Shiro和Spring Security !

简介

image-20200405212036518

Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它实际上是保护基于spring的应用程序的标准。

Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring安全性的真正强大之处在于它可以轻松地扩展以满足定制需求

从官网的介绍中可以知道这是一个权限框架。想我们之前做项目是没有使用框架是怎么控制权限的?对于权限 一般会细分为功能权限,访问权限,和菜单权限。代码会写的非常的繁琐,冗余。

怎么解决之前写权限代码繁琐,冗余的问题,一些主流框架就应运而生而Spring Scecurity就是其中的一种。

一个能够为基于Spring的企业应用系统提供声明式的安全訪问控制解决方式的安全框架(简单说是对访问权限进行控制嘛),应用的安全性包括用户认证(Authentication)用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。 spring security的主要核心功能为认证和授权,所有的架构也是基于这两个核心功能去实现的。

对于上面提到的两种应用情景,Spring Security 框架都有很好的支持。在用户认证方面,Spring Security 框架支持主流的认证方式,包括 HTTP 基本认证、HTTP 表单验证、HTTP 摘要认证、OpenID 和 LDAP 等。在用户授权方面,Spring Security 提供了基于角色的访问控制和访问控制列表(Access Control List,ACL),可以对应用中的领域对象进行细粒度的控制。

认识SpringSecurity

Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!

记住几个类:

  • WebSecurityConfigurerAdapter:自定义Security策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式

Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。

“认证”(Authentication)

身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。

身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。

“授权” (Authorization)

授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。

这个概念是通用的,而不是只在Spring Security 中存在。

框架原理

众所周知 想要对对Web资源进行保护,最好的办法莫过于Filter,要想对方法调用进行保护,最好的办法莫过于AOP。所以springSecurity在我们进行用户认证以及授予权限的时候,通过各种各样的拦截器来控制权限的访问,从而实现安全。

环境搭建

1.新建一个初始的SpringBoot项目web模块,thymeleaf模块。引入 Spring Security 模块

image-20200406193627823

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!--SpringSecurity-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--thymeleaf模板-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>

2.导入静态资源

image-20200405213932009

3.编写controller

image-20200405214050938

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.kylin.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RouterController {

@RequestMapping({"/", "/index"})
public String index() {
System.out.println("index");
return "index";
}

@RequestMapping("/toLogin")
public String toLogin() {
return "views/login";
}

@RequestMapping("/level1/{id}")
public String level1(@PathVariable("id") int id) {
return "views/level1/" + id;
}

@RequestMapping("/level2/{id}")
public String level2(@PathVariable("id") int id) {
return "views/level2/" + id;
}

@RequestMapping("/level3/{id}")
public String level3(@PathVariable("id") int id) {
return "views/level3/" + id;
}
}

4.测试controller跳转是否正常(引入SpringSecurity模块之后会默认把‘/’映射到自带的登录页面,为了测试先注释掉SpringSecurity模块)

GIF

认证和授权

1.编写 Spring Security 配置类(解除注释,重新引用SpringSecurity模块)自定义了一个springSecurity安全框架的配置类 继承WebSecurityConfigurerAdapter,重写其中的方法configure

1
2
3
4
5
6
7
@EnableWebSecurity // 开启WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
}
}

2.定制请求的授权规则

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问,功能页只有对应有权限的人才能访问
//请求授权的规则
http.authorizeRequests()
.antMatchers("/").permitAll()//首页
.antMatchers("/level1/**").hasRole("vip1")//level1下的页面
.antMatchers("/level2/**").hasRole("vip2")//level2下的页面
.antMatchers("/level3/**").hasRole("vip3");//level3下的页面

//没有权限默认会到登录页面
http.formLogin();
//开启注销功能,默认注销后会到登录页面
//http.logout();
//注销后跳到首页

http.logout().logoutSuccessUrl("/");
}

image-20200405221007057

3.再来测试一下

GIF1

发现除了首页都进不去了!因为我们目前没有登录的角色,因为请求需要登录的角色拥有对应的权限才可以!

4.在configure()方法中加入以下配置http.formLogin();,开启自动配置的登录功能!

image-20200405221803284

5.再进行一次测试。发现没有权限的时候会自动跳转到SpringSecurity自带的登录页面。

GIF2

6.我们可以定义认证规则,重写configure(AuthenticationManagerBuilder auth)方法

1
2
3
4
5
6
7
8
9
10
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//在内存中认证,也可以在数据库中认证auth.jdbcAuthentication().这些数据正常应该在数据库中获取
auth.inMemoryAuthentication()
.withUser("kylin").password("123456").roles("vip2","vip3")
.and()
.withUser("root").password("123456").roles("vip1","vip2","vip3")
.and()
.withUser("guest").password("123456").roles("vip1");
}

image-20200405222646420

7.进行测试,我们可以使用这些账号登录进行测试!发现会报错!There is no PasswordEncoder mapped for the id “null”

GIF3

原因是在Springb Security 5.0+ 新增了很多的加密方法。密码必须要以某种加密方式进行密码编码PasswordEncoder否则无法进行登录。

8.将密码进行密码编码

image-20200405223552298

1
2
3
4
5
6
7
8
9
10
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//在内存中认证,也可以在数据库中认证auth.jdbcAuthentication().这些数据正常应该在数据库中获取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("kylin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}

9.测试

GIF4

登录成功,并且每个角色只能访问自己认证下的规则!

权限控制和注销

1.开启自动配置的注销的功能

1
2
3
4
5
6
7
8
//定制请求的授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
//....
//开启自动配置的注销的功能
// /logout 注销请求
http.logout();
}

image-20200406100252655

2.我们在前端,增加一个注销的按钮,index.html 导航栏中

image-20200406100341519

3.我们去测试一下,登录成功之后点击注销发现跳转到了SpringSecurity自带的登录页面。

GIF5

4.但是,我们想让他注销成功后,依旧可以跳转到首页,使用http.logout().logoutSuccessUrl("/");

image-20200406101238211

5.再次进行测试。发现注销成功之后跳转到我的首页。

GIF

6.我们现在又来一个需求:用户没有登录的时候,导航栏上只显示登录按钮,用户登录之后,导航栏可以显示登录的用户信息及注销按钮!还有就是,比如kuangshen这个用户,它只有 vip2,vip3功能,那么登录则只显示这两个功能,而vip1的功能菜单不显示!这个就是真实的网站情况了!该如何做呢?为了解决这个问题我们需要thymeleaf整合SpringSecurity.我们导入依赖。注意thymeleaf整合SpringSecurity目前只支持SpringBoot2.10前的版本!我们降低SpringBoot的版本。否则会发生登录错误!降低版本之后,SpringSecurity的登录页面也会发生变化(变丑…)。

image-20200406132306894

image-20200406130211733

1
2
3
4
5
6
<!--security-thymeleaf整合包-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>

7.修改我们的前端页面,导入命名空间xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"

image-20200406130708779

修改导航栏,增加认证判断

image-20200406131134105

用户登录:sec:authorize="isAuthenticated()"

用户未登录:sec:authorize="!isAuthenticated()"

获取用户名:sec:authentication="name"

获取用户角色权限:sec:authentication="principal.authorities"

8.重启测试,重新登录。显示了我们想要的效果

GIF1319

9.这时候出现了一个问题,当我们注销的时候发生了404错误。原因就是因为它默认防止csrf跨站请求伪造,因为会产生安全问题,我们可以将请求改为post表单提交,或者在spring security中关闭csrf功能。我们试试:在 配置中增加 http.csrf().disable();

image-20200406133050119

我们重新启动,再次进行测试。登录之后正常显示用户名和所拥有的角色权限,能正常的访问所拥有的权限的页面。并且能正常注销。

GIF1332

10.接着完善角色功能认证。也就是登录到相应用户之后根据用户所拥有的权限,首页展示所对应权限能操作的功能模块。

image-20200406133938842

拥有指定权限时:sec:authorize="hasRole('xxx')"

11.进行测试。测试成功

GIF1342

记住我

很多网站的登录页面都有一个记住我的选项。现在我们的情况是我们只要登录之后,关闭浏览器,进入首页就让我们重新登录。因此我们需要实现一个记住我的功能。

1.开启记住我功能http.rememberMe();

image-20200406141717615

2.进行测试。可以发当我登录时选择记住我功能后,关闭浏览器。再次访问首页时,自动登录。测试成功。

GIF1410

原理就是利用了cookie

image-20200406142357696

3.我们点击注销的时候,可以发现,spring security 帮我们自动删除了这个 cookie

image-20200406142554763

4.结论:登录成功后,将cookie发送给浏览器保存,以后登录带上这个cookie,只要通过检查就可以免登录了。如果点击注销,则会删除这个cookie,具体原来和JavaWeb一样。

定制登录页

现在这个项目默认登录都是使用SpringSecurity自带的登录页面,我们现在要使用我们配置的登录页面。

1.再开启SpringSecurity的登录配置后面指定我们想要的loginPagehttp.formLogin().loginPage("/toLogin");

image-20200406143104133

2.然后前端也需要指向我们自己定义的 login请求

1
2
3
<a class="item" th:href="@{/toLogin}">
<i class="address card icon"></i> 登录
</a>

3.我们登录,需要将这些信息发送到哪里,我们也需要配置,login.html 配置提交请求及方式,方式必须为post.在loginPage()源码中的注释说明

image-20200406144002197

image-20200406144116775

如果我们想改变提交username和password的URLloginProcessingUrl("/login")

image-20200406145000979

image-20200406145324563

4.这个请求提交上来,我们还需要验证处理,怎么做呢?我们可以查看formLogin()方法的源码!我们配置接收登录的用户名和密码的参数!usernameParameter("username")passwordParameter("password")

image-20200406145613604

当我们表单中的用户名属性值和密码属性值不为username和password时,要通过配置此参数才能正确接收到用户名和密码来进行验证。

image-20200406145918042

5.在登录页增加记住我的多选框

image-20200406150025184

6.后端验证处理并进行配置记住我的参数。.rememberMeParameter("remember");

image-20200406150439257

7.进行一系列测试。记住我。注销….全部ok

GIF1410

SpringSecurity配置的完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.kylin.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

//AOP
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

//链式编程
//重写configure方法,授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问,功能页只有对应有权限的人才能访问
//请求授权的规则
http.authorizeRequests()
.antMatchers("/").permitAll()//首页
.antMatchers("/level1/**").hasRole("vip1")//level1下的页面
.antMatchers("/level2/**").hasRole("vip2")//level2下的页面
.antMatchers("/level3/**").hasRole("vip3");//level3下的页面
//没有权限默认会到登录页面
// loginPage() – 自定义登录页面
//loginProcessingUrl() – 提交username和password的URL
//defaultSuccessUrl() – 登录成功后跳转的URL
//failureUrl() – 登录失败后跳转的URL
http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login").usernameParameter("username").passwordParameter("password");
//开启注销功能,默认注销后会到登录页面
//http.logout();

//防止网站攻击
http.csrf().disable();//关闭csrf功能
//注销后跳到首页
http.logout().logoutSuccessUrl("/");
//开启记住我功能 cookie,默认保存两周,自定义接收前端的参数
http.rememberMe().rememberMeParameter("remember");
}

//认证
//密码编码:PasswordEncoder
//在Springb Security 5.0+ 新增了很多的加密方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//在内存中认证,也可以在数据库中认证auth.jdbcAuthentication().这些数据正常应该在数据库中获取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("kylin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}

}

项目测试

账号 密码 权限
root 123456 vip1 vip2 vip3
kylin 123456 vip2 vip3
guest 123456 vip1