Spring Boot整合Spring Security总结
一.创建Spring Boot项目
引入Thymeleaf和Web模块以及Spring Security模块方便进行测试,先在pom文件中将 spring-boot-starter-security 的依赖注解掉测试。
二.创建几个用于测试的页面

<!DOCTYPE html><!--index页面-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:action="@{/success}"><input type="submit" value="登录"></form>
<br>
<a th:href="@{/student/query}">查询</a>
<br>
<a th:href="@{/teacher/update}">修改</a>
</body>
</html>
<!DOCTYPE html><!--success页面-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:action="@{/logout}"><input type="submit" value="注销"></form>
<br>
<a th:href="@{/student/query}">查询</a>
<br>
<a th:href="@{/teacher/update}">修改</a>
</body>
</html>
query.html页面和update页面就放一两句话用于测试即可
三.创建控制器
@Controller
public class MyController {
@RequestMapping("/index")
public String index(){
return "index";
}
@RequestMapping("/success")
public String success(){
return "success";
}
@RequestMapping("/student/query")
public String query(){
return "/student/query";
}
@RequestMapping("/teacher/update")
public String update(){
return "/teacher/update";
}
}
四.导入security前

五.导入security模块后
访问任何页面都需要登录,如下图所示:

六.设置权限规则及登录注销
添加一个配置类如下
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
//自定义权限规则
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/index").permitAll() //permitall不需要任何权限
.antMatchers("/student/**").hasRole("student") //需要student权限
.antMatchers("/teacher/**").hasRole("teacher") //需要teacher权限
.antMatchers("/success").hasRole("student"); //需要student权限 //开启登录功能
http.formLogin();
//开启注销功能并指定注销后的页面
http.logout().logoutSuccessUrl("/index");
} //自定义验证规则(如果不开启的话,访问需要权限的页面就会抛出403,拒绝访问)
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//super.configure(auth);
auth.inMemoryAuthentication().withUser("zs").password("123456").roles("student");
auth.inMemoryAuthentication().withUser("ww").password("123456").roles("student","teacher");
}
}
测试:
访问localhost:8080/index后

访问localhost:8080/teacher/update则会跳转到

用对应拥有权限的用户登录后即可进入页面,但是用户权限不够的话还是会出现403错误
注意:如果是Spring Boot2.0.3及以上的版本,登录后会抛java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"异常,这是因为密码没有没有指定加密方式。
解决方案:
添加自定义的PasswordEncoder,代码如下
public class MyPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return s.equals(charSequence.toString());
}
}
并且,自定义验证规则添加上自定义的PasswordEncoder
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("zs").password("123456").roles("student");
auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("ww").password("123456").roles("student","teacher");
}
七.根据登录状态显示信息
1.导入thymeleaf与security整合的模块
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
2.修改页面,例如修改success.html页面
<!DOCTYPE html><!--success页面-->
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div sec:authorize="isAuthenticated()">
<h2><span sec:authentication="name"></span>,您好,您拥有的角色有:
<span sec:authentication="principal.authorities"></span></h2>
</div>
<hr>
<form th:action="@{/logout}" method="post"><input type="submit" value="注销"></form>
<br>
<a th:href="@{/student/query}">查询</a>
<br>
<a th:href="@{/teacher/update}">修改</a>
<div sec:authorize="hasRole('teacher')">如果您拥有teacher这个角色,这句话会显示</div>
</body>
</html>
访问登录后如下图所示

注意:我这里的thymeleaf-extras-springsecurity4版本是3.0.4,但是Spring Boot的版本是2.1.4,可能是jar包冲突问题,sec属性不起作用

解决办法:修改SpringBoot版本到2.0.x及以下,例如本人修改如下:

八.记住用户
可以直接在开启登录功能后添加一行代码即可
http.rememberMe();
九.自定义登录页面
如果不想使用其自带的登录页面,可以在开启登录页面的时候自定义登录页面(注意,xxxx页面中的表单的用户名输入框的name属性和下面对应,密码输入框的name属性也和下面的对应)
http.formLogin().usernameParameter("name").passwordParameter("password").loginPage("/xxxx");
自定义的登录页案例如下
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div align="center">
<form th:action="@{/xxxx}" method="post">
用户名:<input name="name"/><br>
密码:<input name="password"><br/>
<input type="checkbox" name="remeberme"> 记住我<br/>
<input type="submit" value="登陆">
</form>
</div>
</body>
</html>
Spring Boot整合Spring Security总结的更多相关文章
- Spring Boot 整合Spring Data JPA
Spring Boot整合Spring Data JPA 1)加入依赖 <dependency> <groupId>org.springframework.boot</g ...
- Spring boot 整合spring Data JPA+Spring Security+Thymeleaf框架(上)
近期上班太忙所以耽搁了给大家分享实战springboot 框架的使用. 以下是spring boot 整合多个框架的使用. 首先是准备工作要做好. 第一 导入框架所需的包,我们用的事maven 进行 ...
- Spring Boot整合Spring Security
Spring Boot对于该家族的框架支持良好,但是当中本人作为小白配置还是有一点点的小问题,这里分享一下.这个项目是使用之前发布的Spring Boot会员管理系统重新改装,将之前filter登录验 ...
- Spring Boot整合Spring Security自定义登录实战
本文主要介绍在Spring Boot中整合Spring Security,对于Spring Boot配置及使用不做过多介绍,还不了解的同学可以先学习下Spring Boot. 本demo所用Sprin ...
- Spring Boot 整合 Spring Security,用户登录慢
场景 Spring Boot + Spring Security搭建一个Web项目. 临时用了inMemoryAuthentication. @EnableWebSecurity public cla ...
- Spring Boot整合Spring Batch
引言 Spring Batch是处理大量数据操作的一个框架,主要用来读取大量数据,然后进行一定的处理后输出指定的形式.比如我们可以将csv文件中的数据(数据量几百万甚至几千万都是没问题的)批处理插入保 ...
- Spring Boot整合Spring Session实战
传统java web应用session都是由应用服务器(如tomcat)保存在内存中,这对应但节点应用来说没问题:但对于应用集群来说会造成各节点之间的session无法共享,一个节点挂掉后,其他节点接 ...
- Spring Boot 整合Spring Security 和Swagger2 遇到的问题小结
How to configure Spring Security to allow Swagger URL to be accessed without authentication @Configu ...
- spring boot整合spring Data JPA和freemarker
1.spring Data JPA简介 是一个替代hibernate的一个作用于数据库的框架. 2.整合 1.导入依赖 <dependency> <groupId>org.sp ...
随机推荐
- Wazuh 实操
https://www.jianshu.com/p/40c911a5628e?from=timeline&isappinstalled=0
- DeepFaceLab:手动提取高精度脸图,减少抖动!
DeepFaceLab默认情况下都都是自动提取脸部,整体来说效果不错,脸部曲线识别度也比较高.但是自动不是万能的,有些图片的轮廓识别并不好.而识别不好最直接的结果就是合成的视频可能会出现抖动. 也就是 ...
- 关于在IDEA中使用maven projects 的Lifecycle中打包package报expected START_TAG or END_TAG not TEXT
报错指定到maven本地仓库下的settings.xml某一行,如下列JDK配置: <profiles> <profile> <id>jdk-1.8</ ...
- nodejs之express中间件cookie-parser使用
知识点: * .domain的使用,.aaa.com的域名都共享这个cookie信息 * res.cookie(,domain:'.aaa.com'}); * .获取所有cookie,设置cookie ...
- web开发(二) Servlet中response、request乱码问题解决
在网上看见一篇不错的文章,写的详细. 以下内容引用那篇博文.转载于<http://www.cnblogs.com/whgk/p/6412475.html>,在此仅供学习参考之用. 一.re ...
- surface book2 添加自定义分辨率
surface book2 13.5英寸 是3:2的屏幕, 因为默认分辨率3000*2000实在是太高了,看字的时候眼睛有点吃不消 即使开启windows的自定义缩放也有点难受,加上windows ...
- caffe-----silence layer 作用
最近看到prototxt里面有silence这个层,好奇是干什么用的,而且看源码也出奇的简单: #include <vector> #include "caffe/layers/ ...
- Dojo入门:DOM操作
作为一款功能齐全的js工具包,dojo提供了统一的DOM操作方法. dojo.byId dojo.byId 函数使您可以通过 id 属性选择一个 DOM 节点.该函数是标准 document.ge ...
- Day05:循环问题 / 数组
循环嵌套 循环结构中包含完整的循环结构. 注意: 循环嵌套不限层次 各种循环语句都可以互相嵌套 内层循环中出现的break和continue只作用在内层循环中 外层循环循环一次 内层循环循环一遍 Ja ...
- 快速质因数分解及素性测试&ABC142D
首先,这个整数的标准分解非常的显然易见对吧: 一般我们要把一个数分解成这个样子我们可以这样写: #include<cstdio> ],w[],k; void factorize(int n ...