Spring Security 简介
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
- Spring Security 官网:https://spring.io/projects/spring-security#overview
- Spring Security 优点:
- 对身份验证和授权的全面且可扩展的支持
- 防御会话固定,点击劫持,跨站点请求伪造等攻击
- Servlet API集成
- 与Spring Web MVC的可选集成
- …
SpringBoot 集成 Spring Security
1. 实验环境搭建
使用semantic UI 和 jQuery 搭建一个简易的具有三个不同等级的页面,并实现不同页面间的跳转
package cn.mitaowulong.springboot_security2.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("/")
public String index(){
return "index";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "views/login";
}
@RequestMapping("/level1/{id}")
public String level1(@PathVariable int id){
String url = "views/level1/"+id;
return url;
}
@RequestMapping("/level2/{id}")
public String level2(@PathVariable int id){
String url = "views/level2/"+id;
return url;
}
@RequestMapping("/level3/{id}")
public String level3(@PathVariable int id){
String url = "views/level3/"+id;
return url;
}
}
2. 实现授权与认证
需要自定义一个config类,并继承WebSecurityConfigurerAdapter
类,重写其中的用于权限授权的方法configure(HttpSecurity http)
和 用于权限认证的 configure(AuthenticationManagerBuilder auth)
方法,具体见以下代码
package cn.mitaowulong.springboot_security2.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;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问,功能页只有对应的权限才能访问
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限进入登录页面
http.formLogin().loginPage("/toLogin");
//注销功能
http.csrf().disable(); //关闭csrf功能,不关闭防跨站攻击则注销失败
http.logout().logoutSuccessUrl("/"); //注销成功返回首页
//记住我 参数与前端勾选框的name相对应
http.rememberMe().rememberMeParameter("remember");
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//这里Spring Security强制使用一种加密方式
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
//设置root用户能访问所有页面
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
//guest用户只能访问vip1页面
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
此时的index.html文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>首页</title>
<!--semantic-ui-->
<link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
<link th:href="@{/css/qinstyle.css}" rel="stylesheet">
</head>
<body>
<!--主容器-->
<div class="ui container">
<div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
<div class="ui secondary menu">
<a class="item" th:href="@{/}">首页</a>
<!--登录注销-->
<div class="right menu">
<!--登录-->
<a class="item" th:href="@{/toLogin}">
<i class="address card icon"></i> 登录
</a>
<!--注销-->
<a class="item" th:href="@{/logout}">
<i class="address card icon"></i> 注销
</a>
</div>
</div>
</div>
<div class="ui segment" style="text-align: center">
<h3>Spring Security Study</h3>
</div>
<div>
<br>
<div class="ui three column stackable grid">
<div class="column">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 1</h5>
<hr>
<div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
<div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
<div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
</div>
</div>
</div>
</div>
<div class="column">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 2</h5>
<hr>
<div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
<div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
<div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
</div>
</div>
</div>
</div>
<div class="column">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 3</h5>
<hr>
<div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
<div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
<div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script th:src="@{/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/js/semantic.min.js}"></script>
</body>
</html>
至此,已经实现权限授权与认证,再次登录,root用户可访问所有页面,guest用户只能访问level1对应的三个页面,当进入其他页面时会被拦截(403错误)
另外,Spring Security 还可与 Thymeleaf 整合
命名空间:
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
相关依赖:
<!--Spring Scurry 与 Thymeleaf 整合-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
例如可以前端的选择性显示,用户未登录时,显示登陆标签,当用户登录后,则显示注销标签,修改后的前端代码如下
注意(大坑):想实现此功能所使用的的SpringBoot版本最高为2.0.9.RELEASE
如果想实现不同用户对应的权限显示对应的标签,可以如下:
这样就实现了当不同用户登录时显示不同的权限页面,比如现在登录guest用户(只有vip1权限),登录后则会如下:
附:本文中用到的所有Maven依赖
<dependencies>
<!--Spring Scurry 与 Thymeleaf 整合-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>