1.介绍
spring security 的核心功能主要包括:
认证 (你是谁)
授权 (你能干什么)
攻击防护 (防止伪造身份)
实际应用系统中,为了安全起见,一般都必备用户认证(登录)和权限控制的功能,以识别用户是否合法,以及根据权限来控制用户是否能够执行某项操作。
Spring Security是一个安全相关的框架,能够与Spring项目无缝整合,本文主要是介绍Spring Security默认的用户认证和权限控制的使用方法和原理
2.数据库表设计
设计5张表:
user (用户表)
role (角色表)
role_user (用户角色关联表)
jurisdiction (权限表)
role_jurisdiction (角色权限关联表)
每个用户都对应一种角色,但一种角色可以有多个权限
3.示例
3.1. 首先创建一个SpringBoot项目
3.2. 配置说明
我们界面使用Thymeleaf模板
pom.xml引入SpringSecurity、thymeleaf 依赖
<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
application.properties
记得修改成你自己的配置
#thymeleaf配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false
#数据源配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/security?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
#映射文件
mybatis.mapper-locations=classpath:
#实体类起别名
mybatis.type-aliases-package=
#打印语句sql
logging.level.com.lyh.dao=debug
3.3. 创建配置类
配置类需要继承WebSecurityConfigurerAdapter类
重写里面的
configure(HttpSecurity http)、configure(AuthenticationManagerBuilder auth)方法
配置需要认证的url,这里除了登录,其他都需要进行认证
需要使用@EnableWebSecurit启用Security
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsServiceImpl;
@Override
protected void configure(HttpSecurity http) throws Exception {
// 定制请求的授权规则
http.authorizeRequests()
//antMatchers("/add")存放的是请求路径
.antMatchers("/").permitAll()// 首页所有人可以访问
.antMatchers("/add").hasAuthority("ADD")//需要ADD权限才能访问
.antMatchers("/del").hasAuthority("DEL")//需要DEL权限才能访问
.antMatchers("/upd").hasAuthority("UPD")//需要UPD权限才能访问
.antMatchers("/list").hasAuthority("LIST")//需要LIST权限才能访问
.antMatchers("/**")
.fullyAuthenticated()//所有请求都必须登录
.and()
.formLogin()//使用默认的登录表单
.and()
.logout().permitAll();//注销
}
/**
* 用户认证配置
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth