(一)概述
Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架,Spring Security主要做两个事情,认证、授权。我之前写过一篇关于SpringSecurity的博客,但是当时只是介绍了基于mock数据的案例,本期就来介绍一下基于真实数据的认证授权实现。
(二)前期项目搭建
为了更好的展示SpringSecurity,我们先搭建一个简单的web项目出来。引入thymeleaf依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-java8time</artifactId> </dependency>
新建一个登陆页,一个首页,然后几个不同等级的展示页面:
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登陆页</title> </head> <body> <div> <form> <h2>登陆页</h2> <input type="text" id="username" placeholder="username"> <input type="password" id="password" placeholder="password"> <button type="button">登陆</button> </form> </div> </body> </html>
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <div> <h2>首页</h2> <a href="/login" rel="external nofollow" >登陆</a> <div style="overflow: hidden"> <div style="float: left;margin-left: 20px"> <h3>level1</h3> <a href="/level1/1" rel="external nofollow" >level-1-1</a> <hr> <a href="/level1/2" rel="external nofollow" >level-1-2</a> </div> <div style="float: left;margin-left: 20px"> <h3>level2</h3> <a href="/level2/1" rel="external nofollow" >level-2-1</a> <hr> <a href="/level2/2" rel="external nofollow" >level-2-2</a> </div> <div style="float: left;margin-left: 20px"> <h3>level3</h3> <a href="/level3/1" rel="external nofollow" >level-3-1</a> <hr> <a href="/level3/2" rel="external nofollow" >level-3-2</a> </div> </div> </div> </body> </html>
另外还有几个不同等级的页面
分别在body中写上自己对应的编号。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> level-1-1 </body> </html>
最后编写一个controller来接收请求:
@Controller public class RouteController { @RequestMapping({"/","/index"}) public String index(){ return "index"; } @RequestMapping("/login") public String toLogin(){ return "login"; } @RequestMapping("/level1/{id}") public String level1(@PathVariable("id")String id){ return "level1/"+id; } @RequestMapping("/level2/{<mark>来源gaodaimacom搞#^代%!码网</mark>id}") public String level2(@PathVariable("id")String id){ return "level2/"+id; } @RequestMapping("/level3/{id}") public String level3(@PathVariable("id")String id){ return "level3/"+id; } }