目录

1.spring security初识

(1)spring security简介

(2)认证与授权的概念

2.测试环境搭建

2.1  准备html页面

2.2 准备controller

3.spring security安全验证功能测试

3.1 引入spring security

3.2 编写spring security的配置类进行测试练习

(1)在配置类中定义页面的访问权限

(2)开启登录功能

(3)在配置类定义认证规则,指定用户的权限

(4)在配置类中开启注销功能

(5)引入Thymeleaf Extras Springsecurity5 完善功能。

(6)实现记住我功能

(7)自定义登录页面


1.spring security初识

(1)spring security简介

(2)认证与授权的概念

2.测试环境搭建

静态页面目录结构

2.1  准备html页面

(1)level1包下的3个页面

<!--1.html-->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><a th:href="@{/}">返回</a><h1>罗汉拳</h1><p>罗汉拳站当央,打起来不要慌</p>
</body>
</html><!--2.html-->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><a th:href="@{/}">返回</a><h1>武当长拳</h1><p>长一点在长一点</p>
</body>
</html><!--3.html-->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><a th:href="@{/}">返回</a><h1>全真剑法</h1><p>全都是真的</p>
</body>
</html>

(2)level2下的3个html页面

<!--1.html-->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><a th:href="@{/}">返回</a><h1>太极拳</h1><p>一个西瓜圆又圆 劈它一刀成两半 你一半来 给你你不要 给他他不收 那就不给 把两人撵走 他们不走你走 走啦,一挥手,伤自尊不买西瓜别缠我,缓慢纠缠様 两人缠我赖皮,手慢动作左右挥动 看我厉害,转头缓步拍苍蝇状 拍死了,手抱西瓜状+奥特曼十字手+广播操准备运动的站立</p>
</body>
</html><!--2.html-->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><a th:href="@{/}">返回</a><h1>七伤拳</h1><p>练这拳的人全都死了</p>
</body>
</html><!--3.html-->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><a th:href="@{/}">返回</a><h1>梯云纵</h1><p>踩自己的脚往上跳</p>
</body>
</html>

(3)level3下的3个html页面

<!--1.html-->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><a th:href="@{/}">返回</a><h1>葵花宝典</h1><p>欲练神功,挥刀自宫</p>
</body>
</html><!--2.html-->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><a th:href="@{/}">返回</a><h1>龟派气功</h1><p>龟-派-气-功-波</p>
</body>
</html><!--3.html-->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><a th:href="@{/}">返回</a><h1>独孤九剑</h1><p>欲练此剑,必先犯贱</p>
</body>
</html>

(4)初始的welcome.html页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<div ><h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/login}">请登录</a></h2>
</div><hr><div ><h3>普通武功秘籍</h3><ul><li><a th:href="@{/level1/1}">罗汉拳</a></li><li><a th:href="@{/level1/2}">武当长拳</a></li><li><a th:href="@{/level1/3}">全真剑法</a></li></ul></div><div ><h3>高级武功秘籍</h3><ul><li><a th:href="@{/level2/1}">太极拳</a></li><li><a th:href="@{/level2/2}">七伤拳</a></li><li><a th:href="@{/level2/3}">梯云纵</a></li></ul></div><div ><h3>绝世武功秘籍</h3><ul><li><a th:href="@{/level3/1}">葵花宝典</a></li><li><a th:href="@{/level3/2}">龟派气功</a></li><li><a th:href="@{/level3/3}">独孤九剑</a></li></ul>
</div></body>
</html>

(5)login.html暂时不做准备

2.2 准备controller

package security.demo.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;@Controller
public class KungfuController {private final String PREFIX = "pages/";/*** 欢迎页* @return*/@GetMapping("/")public String index() {return "welcome";}/*** 登陆页* @return*/@GetMapping("/userlogin")public String loginPage() {return PREFIX+"login";}/*** level1页面映射* @param path* @return*/@GetMapping("/level1/{path}")public String level1(@PathVariable("path")String path) {return PREFIX+"level1/"+path;}/*** level2页面映射* @param path* @return*/@GetMapping("/level2/{path}")public String level2(@PathVariable("path")String path) {return PREFIX+"level2/"+path;}/*** level3页面映射* @param path* @return*/@GetMapping("/level3/{path}")public String level3(@PathVariable("path")String path) {return PREFIX+"level3/"+path;}}

在浏览器下访问localhost:8080/会转跳到welcome.html页面

并且点击这些超链接都可以转跳到相应页面

至此,一个不带安全验证的微型项目搭建完毕。下面在该项目的基础上加上spring security安全验证功能

3.spring security安全验证功能测试

3.1 引入spring security

在idea的spring initializr中勾选security模块、web模块、thymeleaf模块,自动生成pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.5.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>security</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></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><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

ps:Spring Security的配置类要继承WebSecurityConfigurerAdapter,下面介绍spring security的配置

3.2 编写spring security的配置类进行测试练习

(1)在配置类中定义页面的访问权限

在配置类中配置level1包下的页面访问用户权限为VIP1;level2包下的页面访问用户权限为VIP2;level3包下的页面访问用户权限为VIP3

package security.demo.config;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;/*** @author zhou'en'xian* @date 2020/3/12  20:02*/
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/level1/*").hasRole("vip1").antMatchers("/level2/*").hasRole("vip2").antMatchers("level3").hasRole("vip3");}
}

再次启动项目并访问,由于我们当前什么权限都没有,再次点击超链接,发现不能转跳到相应的页面。

如果我们要访问这些页面,需要一定的权限,首先需要我们在配置类中配置登陆功能,如果没有登录、没有权限就会来到登陆页面。同时我们也可以在配置类定义认证规则,指定用户的权限。

(2)开启登录功能

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();}

(3)在配置类定义认证规则,指定用户的权限

@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("张三").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");}

此时,我们在进入welcome.html点击里面的超链接,由于我们没有 权限,会来到登录页面(注意这个登录页面是spring boot默认的页面,我们没有编写自定义登录页面会走默认)

默认登录页面

登录以后,如果用户有访问权限,则可以进入相应页面。

(4)在配置类中开启注销功能

 @Overrideprotected 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("/");}

同时,在welcome.html加入

<div><form th:action="@{/logout}" method="post"><input type="submit" value="注销"/></form>
</div>

此时,welcome.html

<!DOCTYPE html>
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<div ><h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/login}">请登录</a></h2>
</div>
<div><form th:action="@{/logout}" method="post"><input type="submit" value="注销"/></form>
</div><hr><div ><h3>普通武功秘籍</h3><ul><li><a th:href="@{/level1/1}">罗汉拳</a></li><li><a th:href="@{/level1/2}">武当长拳</a></li><li><a th:href="@{/level1/3}">全真剑法</a></li></ul></div><div ><h3>高级武功秘籍</h3><ul><li><a th:href="@{/level2/1}">太极拳</a></li><li><a th:href="@{/level2/2}">七伤拳</a></li><li><a th:href="@{/level2/3}">梯云纵</a></li></ul></div><div ><h3>绝世武功秘籍</h3><ul><li><a th:href="@{/level3/1}">葵花宝典</a></li><li><a th:href="@{/level3/2}">龟派气功</a></li><li><a th:href="@{/level3/3}">独孤九剑</a></li></ul>
</div></body>
</html>

welcome.html页面

可以看到,页面中已经显示注销按钮了,点击按钮可以注销。但是,还有一个问题,我已经登录了,但是页面还是和没登陆前一样,我现在想要这样做:登录后显示用户信息,根据用户权限显示页面,如果用户没有权限访问一些页面,那么就在首页隐藏进入该页面的超链接。我们可以借助thymeleaf对spring security的支持,完成相应的功能。

(5)引入Thymeleaf Extras Springsecurity5 完善功能。

在pom.xml文件中引入 Thymeleaf Extras Springsecurity5 的依赖。

<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 -->
<dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity5</artifactId><version>3.0.4.RELEASE</version>
</dependency>

同时在welcome.html文件中引入spring security的名称空间

xmlns:sec="http://www.thymeleaf.org/extras/spring-security"

继续完善welcome.html页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<!--如果用户没有登录,则显示登录超链接-->
<div sec:authorize="!isAuthenticated()"><h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/login}">请登录</a></h2>
</div>
<!--如果用户登录了显示用户信息,同时显示注销按钮-->
<div sec:authorize="isAuthenticated()"><h2><span sec:authentication="name"></span>你好,您的身份<span sec:hentication="principal.authorities"></span></h2><form th:action="@{/logout}" method="post"><input type="submit" value="注销"/></form>
</div><hr>
<!--用户身份为VIP1的授权访问-->
<div sec:authorize="hasRole('vip1')"><h3>普通武功秘籍</h3><ul><li><a th:href="@{/level1/1}">罗汉拳</a></li><li><a th:href="@{/level1/2}">武当长拳</a></li><li><a th:href="@{/level1/3}">全真剑法</a></li></ul></div>
<!--用户身份为VIP2的授权访问-->
<div sec:authorize="hasRole('vip2')"><h3>高级武功秘籍</h3><ul><li><a th:href="@{/level2/1}">太极拳</a></li><li><a th:href="@{/level2/2}">七伤拳</a></li><li><a th:href="@{/level2/3}">梯云纵</a></li></ul></div>
<!--用户身份为VIP3的授权访问-->
<div sec:authorize="hasRole('vip3')"><h3>绝世武功秘籍</h3><ul><li><a th:href="@{/level3/1}">葵花宝典</a></li><li><a th:href="@{/level3/2}">龟派气功</a></li><li><a th:href="@{/level3/3}">独孤九剑</a></li></ul>
</div></body>
</html>

没登陆时,页面不显示其他页面的超链接

用张三用户登录

(6)实现记住我功能

在配置类的方法中开启

  @Overrideprotected 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("/");//开启记住我功能http.rememberMe();}

再次进入默认的登录页面

默认的cookie有效时间为14天。登陆成功以后,将cookie发给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以免登录,点击注销会删除cookie。

(7)自定义登录页面

 @Overrideprotected void configure(HttpSecurity http) throws Exception {//自定义授权规则http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/level1/*").hasRole("vip1").antMatchers("/level2/*").hasRole("vip2").antMatchers("level3").hasRole("vip3");//开启登录功能http.formLogin().usernameParameter("user").passwordParameter("pwd").loginPage("/userlogin");//开启注销功能//注销以后,转跳到首页http.logout().logoutSuccessUrl("/");//开启记住我功能http.rememberMe().rememberMeParameter("reme");}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("张三").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");}
}

login.html为自己定义的登录页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body><h1 align="center">欢迎登陆武林秘籍管理系统</h1><hr><div align="center"><form th:action="@{/userlogin}" method="post">用户名:<input name="user"/><br>密码:<input name="pwd"><br/><input type="checkbox" name="reme"> 记住我<br/><input type="submit" value="登陆"></form></div>
</body>
</html>

SpringBoot整合SpringSecurity相关推荐

  1. Springboot整合SpringSecurity 04-启用登出logout功能

    Springboot整合SpringSecurity 04-启用登出logout功能 前面Springboot整合SpringSecurity 02-使用自定义登陆页面我们讲过了SpringSecur ...

  2. Springboot 整合SpringSecurity实现账号密码+手机验证码登陆

    Springboot 整合SpringSecurity实现账号密码+手机验证码登陆 示例说明 版本 示例安装 Spring-security 介绍 为什么不用 shiro Spring-Securit ...

  3. SpringBoot整合SpringSecurity+Redis权限控制

    SpringBoot整合SpringSecurity+Redis权限控制 1.认识SpringSecurity 2.效果截图 2.1.登录接口 2.2.注册接口 2.3.管理员权限接口 2.4.普通用 ...

  4. SpringBoot整合SpringSecurity实现权限控制(五):用户管理

    系列文章目录 <SpringBoot整合SpringSecurity实现权限控制(一):实现原理> <SpringBoot整合SpringSecurity实现权限控制(二):权限数据 ...

  5. springboot整合springsecurity安全框架(后端spring_security模块代码可直接使用,根据需求自定义修改)

    SpringSecurity简介 最下面有与springboot整合的模块代码 用户认证和用户授权 主要包含两部分:用户认证和用户授权 用户认证:进入用户登录时候,输入用户名密码,查询数据库查看是否正 ...

  6. SpringBoot整合SpringSecurity [超详细] (一)入门案例

    文章目录 前言 1. 主流安全框架有哪些 2. Spring Security为什么越来越火 3. 为什么现在越来越多的人选择Spring Security 一.Spring Security 简介 ...

  7. springboot整合springSecurity使用

    1.导入依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>sp ...

  8. springboot整合springsecurity时出现了localhost将您重定向次数过多 循环地址错误解决

    如图,在重定向页面时发生了地址循环的现象,错误是重定向次数过多 查看代码,为了跳转到我们自己定义的登录页面,写了loginPage("/login.html"),按照正常的逻辑,应 ...

  9. springboot整合之版本号统一管理

    特别说明:本次项目整合基于idea进行的,如果使用Eclipse可能操作会略有不同,不过总的来说不影响. springboot整合之如何选择版本及项目搭建 springboot整合之版本号统一管理  ...

最新文章

  1. ゾーン10進数、パック10進数
  2. JVM 常用的基本配置有哪些?
  3. Java判断一组数字是否是等差数列
  4. 回到顶部最简单的JQuery实现代码
  5. 参考文献_参考文献:
  6. 如何对mysql做物理备份_如何创建物理MySQL备份
  7. 服务型存储市场的现状
  8. poj 1734 (最小环)
  9. 获得手机屏幕相关参数
  10. git 使用http方式的一个小问题
  11. 人工智能-基于规则的专家系统(基础知识)
  12. [电脑桌面壁纸]macOS Big Sur 桌面壁纸分享
  13. 仿迅雷播放器教程 -- 媒体播放器对比 (2)
  14. 辐射4核能选项用计算机失败,辐射4NMM安装framework失败解决方法一览_游侠网
  15. 2023北京航空航天大学计算机考研信息汇总
  16. 计算机软件考试大纲,求计算机软件资格考试大纲和复习资料
  17. mkv格式用什么播放器打开?视频转换器怎样操作
  18. 前端基础-html-01
  19. vue实现跑马灯抽奖
  20. 【Tool】常用 GIT 命令参阅

热门文章

  1. 第二代计算机的主要应用领域,第二代计算机的主要应用领域是啥
  2. 计算机病毒语音,新病毒:让被感染的计算机发出语音提醒
  3. 小程序 键盘挡住底部输入框解析
  4. 从概念到现状,一文读懂边缘计算
  5. C# 8.0核心技术指南
  6. 5G的五项核心技术和5.5G相关的技术
  7. php trie,数据结构-PHP 字典树(Trie)的实现
  8. 或许微软真的错了,全端 App 的时代要到来了
  9. 金融工程---引论以及参考书目
  10. python用七巧板图片画个图_canvas 入门-利用 canvas 制作一个七巧板