在这一节,我们将对/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的更多相关文章

  1. spring boot(二)整合mybatis plus+ 分页插件 + 代码生成

    先创建spring boot项目,不知道怎么创建项目的 可以看我上一篇文章 用到的环境 JDK8 .maven.lombok.mysql 5.7 swagger 是为了方便接口测试 一.Spring ...

  2. [Spring] 学习Spring Boot之二:整合MyBatis并使用@Trasactional管理事务

    一.配置及准备工作 1.在 Maven 的 pom 文件中新增以下依赖: <dependency> <groupId>mysql</groupId> <art ...

  3. Spring Boot教程(十七)属性配置文件详解(2)

    通过命令行设置属性值 相信使用过一段时间Spring Boot的用户,一定知道这条命令:java -jar xxx.jar --server.port=8888,通过使用–server.port属性来 ...

  4. SpringBoot进阶教程(二十七)整合Redis之分布式锁

    在之前的一篇文章(<Java分布式锁,搞懂分布式锁实现看这篇文章就对了>),已经介绍过几种java分布式锁,今天来个Redis分布式锁的demo.redis 现在已经成为系统缓存的必备组件 ...

  5. 学习Spring Boot:(十七)Spring Boot 中使用 Redis

    前言 Redis 1 是一个由Salvatore Sanfilippo写的key-value存储系统. edis是一个开源的使用ANSI C语言编写.遵守BSD协议.支持网络.可基于内存亦可持久化的日 ...

  6. spring boot使用freemarker模版整合spring Data JPA

    目录结构 第一步:在pom.xml文件中添加依赖 <!--模板依赖--> <dependency> <groupId>org.springframework.boo ...

  7. Spring Boot2 系列教程(二十四)Spring Boot 整合 Jpa

    Spring Boot 中的数据持久化方案前面给大伙介绍了两种了,一个是 JdbcTemplate,还有一个 MyBatis,JdbcTemplate 配置简单,使用也简单,但是功能也非常有限,MyB ...

  8. Spring Boot2 系列教程(二十八)Spring Boot 整合 Session 共享

    这篇文章是松哥的原创,但是在第一次发布的时候,忘了标记原创,结果被好多号转发,导致我后来整理的时候自己没法标记原创了.写了几百篇原创技术干货了,有一两篇忘记标记原创进而造成的一点点小小损失也能接受,不 ...

  9. Spring Boot教程(三十七)整合MyBatis

    Spring中整合MyBatis就不多说了,最近大量使用Spring Boot,因此整理一下Spring Boot中整合MyBatis的步骤.搜了一下Spring Boot整合MyBatis的文章,方 ...

  10. Spring Boot教程(二十二)使用Swagger2构建强大的RESTful API文档(1)

    由于Spring Boot能够快速开发.便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API.而我们构建RESTful API的目的通常都是由于多终端的原因,这 ...

随机推荐

  1. thinkPHP验证码报错: Call to undefined function captcha_src()

    问题出现的原因可能有: 1. captcha扩展缺失: 2. captcha扩展与当前thinkPHP版本不兼容. thinkPHP6.0以下版本只能使用 captcha2.0以下版本,不支持2.0版 ...

  2. postgres 常规操作杂记

    分布式:1.扩容不方便(数据重分布)2.分布键变更很麻烦3.分布键选择(架构设计)谨慎4.跨库join性能差5.分布式事务性能差6.sql限制多,功能确实多7.应用改造成本巨大8.全局一致性时间点恢复 ...

  3. javaweb中的标签的核心标签库的常用标签

    //标签的使用使得页面的代码更加简洁,jsp脚本的尽可能少的使用,所以熟练掌握标签对于开发是很有必要的 <%--set设置数据,默认在page域 --%> <c:set var=&q ...

  4. 19、Firewalld防火墙

    安全的考虑方向: 安全框架 OSI七层模型 硬件 机架上锁(机柜) 温度 硬件检查 网络 iptables/firewalld 仅允许公司的IP地址能连接服务器的22端口 公有云使用 安全组 系统 没 ...

  5. poj 1007 DNA sorting (qsort)

    DNA Sorting Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 95209   Accepted: 38311 Des ...

  6. 2019.9.20使用kali中的metasploi获取windows 的权限

    1 kali 基于debin的数字取证系统,上面集成了很多渗透测试工具,其前身是bt5r3(bractrack) 其中Metasploit是一个综合利用工具,极大提高攻击者渗透效率,使用ruby开发的 ...

  7. mongo启动报错问题处理

    关键错误信息child process failed, exited with error number 100 这是服务器断电导致数据库意外关闭导致的问题,处理方法也比较简单 rm -rf /var ...

  8. BLE 5协议栈-物理层

    文章转载自:http://www.sunyouqun.com/2017/04/page/4/ 1. 简介 物理层(Physical Layer)是BLE协议栈最底层,它规定了BLE通信的基础射频参数, ...

  9. CentOS 7 安装 gcc 4.1.2

    CentOS 7 安装 gcc 4.1.2 0. 参考 在centOS7.2上编译gcc4.1.2 1. 安装了编译所需 yum groupinstall "Development Tool ...

  10. vim简明教程--半小时从入门到精通

    https://download.csdn.net/download/qccz123456/10567716 vim三种模式:命令模式.插入模式.底行模式.使用ESC.i.:切换模式. vim [路径 ...