1、 Spring Security
1.1、概述
Spring Security
是一个能够为基于 Spring
的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在 Spring
应用上下文中配置的 Bean
,充分利用了 Spring IoC
, DI
(控制反转 Inversion of Control
, DI:Dependency Injection
依赖注入)和 AOP
(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
WebSecurityConfigurerAdapter
:自定义Security
策略AuthenticationManagerBuilder
:自定义认证策略@EnableWebSecurity
:开启WebSecurity
模式
Spring Security
的两个主要目标是“认证”和”授权“(访问控制)
Authentication
:认证Authorization
:授权
1.2、配置使用
1.2.1、导入 jar
包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
1.2.2、配置类
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 认证方法
* @param http
* @throws Exception
*/
@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();
// 注销成功后跳转到主页
http.logout().logoutSuccessUrl("/");
}
/**
* 授权方法
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/**
* 版本为 spring boot 2.1.x 可以不用使用密码加密
* 在 spring boot 2.1.x 之上版本需要使用密码加密
* 加密方式 .passwordEncoder(new XXXPasswordEncoder())
*/
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("vip1","vip2","vip3")
.and().withUser("vip1").password(new BCryptPasswordEncoder().encode("admin")).roles("vip1")
.and().withUser("vip2").password(new BCryptPasswordEncoder().encode("admin")).roles("vip1","vip2")
.and().withUser("vip3").password(new BCryptPasswordEncoder().encode("admin")).roles("vip1","vip2","vip3");
}
}
1.2.3、整合 thymeleaf
- 导入包
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
若
spring boot
版本为2.1.x
则使用thymeleaf-extras-springsecurity4
index.html
<!DOCTYPE html>
<!--导入相关约束-->
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>index</h1>
<!--若已登录则显示注销链接-->
<div sec:authorize="isAuthenticated()">
<a th:href="@{/logout}">logout</a>
</div>
<!--未登录显示登录链接-->
<div sec:authorize="!isAuthenticated()">
<a th:href="@{/login}">login