Spring Boot教程(二十七)整合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");
} }
- 通过
@EnableWebSecurity
注解开启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。
Spring Boot教程(二十七)整合Spring Security的更多相关文章
- spring boot(二)整合mybatis plus+ 分页插件 + 代码生成
先创建spring boot项目,不知道怎么创建项目的 可以看我上一篇文章 用到的环境 JDK8 .maven.lombok.mysql 5.7 swagger 是为了方便接口测试 一.Spring ...
- [Spring] 学习Spring Boot之二:整合MyBatis并使用@Trasactional管理事务
一.配置及准备工作 1.在 Maven 的 pom 文件中新增以下依赖: <dependency> <groupId>mysql</groupId> <art ...
- Spring Boot教程(十七)属性配置文件详解(2)
通过命令行设置属性值 相信使用过一段时间Spring Boot的用户,一定知道这条命令:java -jar xxx.jar --server.port=8888,通过使用–server.port属性来 ...
- SpringBoot进阶教程(二十七)整合Redis之分布式锁
在之前的一篇文章(<Java分布式锁,搞懂分布式锁实现看这篇文章就对了>),已经介绍过几种java分布式锁,今天来个Redis分布式锁的demo.redis 现在已经成为系统缓存的必备组件 ...
- 学习Spring Boot:(十七)Spring Boot 中使用 Redis
前言 Redis 1 是一个由Salvatore Sanfilippo写的key-value存储系统. edis是一个开源的使用ANSI C语言编写.遵守BSD协议.支持网络.可基于内存亦可持久化的日 ...
- spring boot使用freemarker模版整合spring Data JPA
目录结构 第一步:在pom.xml文件中添加依赖 <!--模板依赖--> <dependency> <groupId>org.springframework.boo ...
- Spring Boot2 系列教程(二十四)Spring Boot 整合 Jpa
Spring Boot 中的数据持久化方案前面给大伙介绍了两种了,一个是 JdbcTemplate,还有一个 MyBatis,JdbcTemplate 配置简单,使用也简单,但是功能也非常有限,MyB ...
- Spring Boot2 系列教程(二十八)Spring Boot 整合 Session 共享
这篇文章是松哥的原创,但是在第一次发布的时候,忘了标记原创,结果被好多号转发,导致我后来整理的时候自己没法标记原创了.写了几百篇原创技术干货了,有一两篇忘记标记原创进而造成的一点点小小损失也能接受,不 ...
- Spring Boot教程(三十七)整合MyBatis
Spring中整合MyBatis就不多说了,最近大量使用Spring Boot,因此整理一下Spring Boot中整合MyBatis的步骤.搜了一下Spring Boot整合MyBatis的文章,方 ...
- Spring Boot教程(二十二)使用Swagger2构建强大的RESTful API文档(1)
由于Spring Boot能够快速开发.便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API.而我们构建RESTful API的目的通常都是由于多终端的原因,这 ...
随机推荐
- ps -ef
status, msg = commands.getstatusoutput("ps -ef | grep start.sh | grep -Fv grep | awk '{print $1 ...
- 最长上升子序列(Longest increasing subsequence)
问题描述 对于一串数A={a1a2a3…an},它的子序列为S={s1s2s3…sn},满足{s1<s2<s3<…<sm}.求A的最长子序列的长度. 动态规划法 ...
- Java Lock的使用
+ ReentrantLock类的使用 + ReentrantReadWriteLock类的使用 1. 使用ReentrantLock类 ReentrantLock类能够实现线程之间同步互斥,并且在扩 ...
- win10操作系统的安装
电脑被重装操作系统了,一切从头开始啦!!! 不过倒是学习了,给大家分享一些学习经验~ 1:制作启动盘 制作启动盘的首先要准备一个空的U盘,为什么说空的呢,因为制作的时候会格式化U盘,只能存个操作系统, ...
- WPF中Matrix介绍
最近在做一些图形变换操作的功能,图形变换涉及大学中的矩阵运算部分的知识,又重新复习了一下矩阵.这里做一下记录.由于不知道矩阵如何输入,一个个截图又麻烦,所以这里就全部用截图了^-^.
- O005、远程管理 KVM 虚机
参考https://www.cnblogs.com/CloudMan6/p/5256018.html 上一节我们通过 virt-manager 在本地主机上创建并管理 KVM 虚机,其实 virt ...
- 关于CSRF 和 csrftoken
CSRF 虽然利用了session验证机制的漏洞,一般使用加密token的方式防御,但是其本身和session以及JWT token没有直接联系. 描述 CSRF利用用户正常登录产生的cookie,利 ...
- Java中的Switch....case语句:
一.格式: switch(表达式){ case 常量表达式1: 语句1; case 常量表达式2: 语句2; … case 常量表达式n: 语句n; default: ...
- 09 Python两种创建类的方式
第一种比较普遍的方式: class Work(): def __init__(self,name): self.name = name w = Work('well woker') 这样就简单创建了一 ...
- String和StringBuffer的常见用法
链接:https://www.nowcoder.com/questionTerminal/fe6b651b66ae47d7acce78ffdd9a96c7?answerType=1&f=dis ...