Springboot整合SpringSecurity
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
首先创建一个springboot项目,在templates目录下写一些简单的页面。
index.html
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml" xmlns:sec="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
index
</div>
<h1>
欢迎
</h1>
<a th:href="@{/add}">添加</a>
<a th:href="@{/delete}">删除</a>
<a th:href="@{/toLogin}">登录</a>
<a th:href="@{logout}">注销</a>
</body>
</html>
导入依赖
<!--thymeleaf集成springsecurity4-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--spring-security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
创建controller,把页面跳转的方法写上
@Controller
public class routerController {
@RequestMapping({"/","index"})
public String index(){//跳转首页的方法
return "index";
}
@RequestMapping("/add")
public String add(){//跳转添加页的方法
return "add";
}
@RequestMapping("/delete")
public String delete(){//跳转删除页的方法
return "delete";
}
@RequestMapping("/toLogin")
public String toLogin(){//跳转登录页的方法
return "login";
}
}
现在从首页是可以访问到其他页面的
Security配置
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {}
配置权限,只有有addRole权限才可以进入/add,只有有deleteRole权限才可以进入/delete,开启登录页,没有权限时可以跳转到登录页面
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问 permitAll()所有/请求能通过
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/add").hasRole("addRole") //添加请求需要addRole权限
.antMatchers("/delete").hasRole("deleteRole");//删除请求需要deleteRole权限
//开启登录页
http.formLogin();
}
现在访问添加和删除页面都是不能访问的,点击后没有权限可以跳转到登录页面,只能访问首页和登录页面
配置用户,配置了一个账号为zhangsan,密码是123456的账号,拥有addRole权限
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())//必须开启加密验证 才能访问成功 不然登录失败
//添加一个zhangsan用户 账号为zhangsan 密码为加密的密码new BCryptPasswordEncoder().encode("123456") 拥有的权限为 addRole
.withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("addRole");
}
登录可以访问add页面,不能访问delete页面
开启注销功能
//开启注销功能 默认的url:/logout
http.logout().logoutSuccessUrl("/index");