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的目的通常都是由于多终端的原因,这 ...
随机推荐
- 使用history.js解决浏览器对history使用的兼容问题
history.js即可以解决禁止浏览器回退的浏览器兼容问题,也能解决直接修改浏览器当前标签页url的浏览器兼容问题. 解决禁止浏览器回退: <script src="../../js ...
- GitHub从小白到熟悉<五>
GitHub 主页
- createTextNode() 方法和createTextNode()方法
<!DOCTYPE html><html><head><meta charset="utf-8"><title>菜鸟教程 ...
- tomcat启动报ClassNotFound
排除本来就缺少该类的原因,经过自己经验和网上查的资料,解决方式如下: jar包冲突(关闭其他项目) eclipse的java版本不对,点击项目,右键properties在project facets, ...
- luogu题解 UVA534 【Frogger--最小瓶颈边
题目链接: https://www.luogu.org/problemnew/show/UVA534 Update 6.18 多点对最短瓶颈路算法:https://www.cnblogs.com/Ry ...
- MySQL 主从同步架构中你不知道的“坑”(2)
指定同步库情况 1.binlog_format= ROW模式 mysql> use testdb; Database changed mysql> show tables; +----- ...
- java实现spark常用算子之flatmap
import org.apache.spark.SparkConf;import org.apache.spark.api.java.JavaRDD;import org.apache.spark.a ...
- 记录一次维护weblogic集群的问题
[问题描述] weblogic 集群子服务节点启动,启动完毕后状态改为 ADMIN,正常情况是 RUNNING 在启动脚本添加如下配置即可 -DDomainRegistrationEnabled=tr ...
- js 继承的简单理解
什么是继承 js中的继承就是获取存在对象已有属性和方法的一种方式. 继承一 属性拷贝 就是将对象的成员复制一份给需要继承的对象. // 创建父对象 var superObj = { name:'liy ...
- Redis常见的七种使用场景
简单字符串缓存实战简单队列实战简单发布订阅实战简单计数器实战排行榜实战简单字符串悲观锁实战简单事务的乐观锁实战 简单字符串缓存实战 $redis->connect('127.0.0.1', ...