Spring Boot如何使用Spring Security进行安全控制
作者:Joker_Ye 发布时间:2022-03-26 03:59:41
我们在编写Web应用时,经常需要对页面做一些安全控制,比如:对于没有访问权限的用户需要转到登录表单页面。要实现访问控制的方法多种多样,可以通过Aop、 * 实现,也可以通过框架实现(如:Apache Shiro、spring Security)。
本文将具体介绍在Spring Boot中如何使用Spring Security进行安全控制。
准备工作
首先,构建一个简单的Web工程,以用于后续添加安全控制,也可以用之前Chapter3-1-2 做为基础工程。若对如何使用Spring Boot构建Web应用,可以先阅读 《Spring Boot开发Web应用》 一文。
Web层实现请求映射
@Controller
public class HelloController {
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("/hello")
public String hello() {
return "hello";
}
}
/ :映射到index.html
/hello :映射到hello.html
实现映射的页面
src/main/resources/templates/index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security入门</title>
</head>
<body>
<h1>欢迎使用Spring Security!</h1>
<p>点击 <a th:href="@{/hello}" rel="external nofollow" >这里</a> 打个招呼吧</p>
</body>
</html>
src/main/resources/templates/hello.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
可以看到在index.html中提供到 /hello 的链接,显然在这里没有任何安全控制,所以点击链接后就可以直接跳转到hello.html页面。
整合Spring Security
在这一节,我们将对 /hello 页面进行权限控制,必须是授权用户才能访问。当没有权限的用户访问后,跳转到登录页面。
添加依赖
在pom.xml中添加如下配置,引入对Spring Security的依赖。
<dependencies>
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
...
</dependencies>
Spring Security配置
创建Spring Security的配置类 WebSecurityConfig ,具体如下:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
通过 @EnableWebMvcSecurity 注解开启Spring Security的功能
继承 WebSecurityConfigurerAdapter ,并重写它的方法来设置一些web安全的细节
configure(HttpSecurity http) 方法
通过 authorizeRequests() 定义哪些URL需要被保护、哪些不需要被保护。例如以上代码指定了 / 和 /home 不需要任何认证就可以访问,其他的路径都必须通过身份验证。
通过 formLogin() 定义当需要用户登录时候,转到的登录页面。
configureGlobal(AuthenticationManagerBuilder auth) 方法,在内存中创建了一个用户,该用户的名称为user,密码为password,用户角色为USER。
新增登录请求与页面
在完成了Spring Security配置之后,我们还缺少登录的相关内容。
HelloController中新增 /login 请求映射至 login.html
@Controller
public class HelloController {
// 省略之前的内容...
@RequestMapping("/login")
public String login() {
return "login";
}
}
新增登录页面: src/main/resources/templates/login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
用户名或密码错
</div>
<div th:if="${param.logout}">
您已注销成功
</div>
<form th:action="@{/login}" method="post">
<div><label> 用户名 : <input type="text" name="username"/> </label></div>
<div><label> 密 码 : <input type="password" name="password"/> </label></div>
<div><input type="submit" value="登录"/></div>
</form>
</body>
</html>
可以看到,实现了一个简单的通过用户名和密码提交到 /login 的登录方式。
根据配置,Spring Security提供了一个过滤器来拦截请求并验证用户身份。如果用户身份认证失败,页面就重定向到 /login?error ,并且页面中会展现相应的错误信息。若用户想要注销登录,可以通过访问 /login?logout 请求,在完成注销之后,页面展现相应的成功消息。
到这里,我们启用应用,并访问 http://localhost:8080/ ,可以正常访问。但是访问 http://localhost:8080/hello 的时候被重定向到了 http://localhost:8080/login 页面,因为没有登录,用户没有访问权限,通过输入用户名user和密码password进行登录后,跳转到了Hello World页面,再也通过访问 http://localhost:8080/login?logout ,就可以完成注销操作。
为了让整个过程更完成,我们可以修改 hello.html ,让它输出一些内容,并提供“注销”的链接。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="注销"/>
</form>
</body>
</html>
本文通过一个最简单的示例完成了对Web应用的安全控制,Spring Security提供的功能还远不止于此,更多Spring Security的使用可参见 Spring Security Reference 。
完整示例: Chapter4-3-1
来源:http://blog.csdn.net/hj7jay/article/details/51730284


猜你喜欢
- java金钱处理方法实例详解在支付行业中,涉及到对金钱的处理比较多。比如分转化成元、费率计算、手续费计算等等。1.分转化成元/** &nb
- SpringBoot 2.1.4 错误处理机制springboot的自动配置中帮我们配置了相关的错误处理组件,例如访问一个不存在的页面,就会
- 之前使用的那台电脑有点旧了,稍微跑一下程序就报内存不够。本来想考虑入手一台带GPU的新电脑,在商品浏览里的时候,考虑到钱包不够厚实。就选了家
- 本文实例讲述了Java生产者消费者模式。分享给大家供大家参考,具体如下:java的生产者消费者模式,有三个部分组成,一个是生产者,一个是消费
- 概述在移动应用开发中,消息推送可以说是一项非常重要的功能,它能够起到提醒或者唤醒用户的作用,同时也是产品运营人员更高效地实现运营目标的重要手
- @Lazy用于指定该Bean是否取消预初始化。主要用于修饰Spring Bean类,用于指定该Bean的预初始化行为,使用该Annotati
- springboot 针对jackson是自动化配置的,如果需要修改,有两种方式:方式一:通过application.yml配置属性说明:#
- 很不错的蓝牙通信demo实现发送和接受功能,就用了两个类就实现了,具体内容如下说下思路把 主要有两个类 主界面类 和 蓝牙聊天服务类&nbs
- 本文实例为大家分享了java实现通讯录管理系统的具体代码,供大家参考,具体内容如下完成项目的流程:1.根据需求,确定大体方向 2.功能模块分
- Stream简化元素计算一、接口设计从Java1.8开始提出了Stream流的概念,侧重对于源数据计算能力的封装,并且支持序列与并行两种操作
- 文件上传是网站非常常用的功能,直接使用Servlet获取上传文件还得解析请求参数,比较麻烦,所以一般选择采用apache的开源工具,comm
- 使用System.Environment获取电脑的相关属性,入门案例,具体内容如下static void Main(string[] arg
- 本文实例讲述了C#获取文件创建时间的方法。分享给大家供大家参考。具体如下:C#获取文件创建时间,主要用到了FileInfo的Creattio
- 前言Lifecycle是Jetpack架构组件中用来感知生命周期的组件,使用Lifecycles可以帮助我们写出和生命周期相关更简洁更易维护
- 前言:在纯 Java 代码里 我们一般都会用class.getResource(String name) 或者 class.getClass
- java应用CPU有波动,事后怎么分析?目前我采用的方案是根据CPU负载自动执行jstack,并将文件上传到OSS。 环境:阿里云
- 本文实例为大家分享了Java模拟HTTP Get Post请求,校园BBS自动回帖功能,供大家参考,具体内容如下设计思路找到帖子链接的集合,
- 介绍try-with-resources是Java中的环绕语句之一,旨在减轻开发人员释放try块中使用的资源的义务。它最初在Java 7中引
- 前言 随着Java生态愈发庞大,各种各样的新技术层出不穷,这也给大家的学习带来了很多困惑,这么多技术我该学什么,盲目的在各种新技术间
- 一、分析 本次博客,主要解决文件上传等一系列问题,将从两方面来论述,