我们在编写Web应用时,经常需要对页面做一些安全控制,比如:对于没有访问权限的用户需要转到登录表单页面。要实现访问控制的方法多种多样,可以通过Aop、拦截器实现,也可以通过框架实现(如:Apache Shiro、Spring Security)。

本文将具体介绍在Spring Boot中如何使用Spring Security进行安全控制。

准备工作

首先,构建一个简单的Web工程,以用于后续添加安全控制,也可以用之前Chapter3-1-2做为基础工程。若对如何使用Spring Boot构建Web应用,可以先阅读《Spring Boot开发Web应用》一文。

Web层实现请求映射

@Controllerpublic 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}">这里</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@EnableWebSecuritypublic 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

@Controllerpublic 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目录:

  • Github:https://github.com/dyc87112/SpringBoot-Learning
  • Gitee:https://gitee.com/didispace/SpringBoot-Learning

如果您觉得本文不错,欢迎Star支持,您的关注是我坚持的动力!


Spring Boot中使用Spring Security进行安全控制相关推荐

  1. Spring boot中使用Spring Security的记住我 remember-me功能

    Spring boot中使用Spring Security的记住我 remember-me功能 问题描述:Spring security新手,在登录时加上记住我功能,需要使用框架自带的记住我. 记住的 ...

  2. java 方式配置ssm,关于SSM以及Spring boot中对于Spring MVC配置的问题

    SSM中 Spring MVC配置 传统的web.xml配置 web.xml contextConfigLocation classpath*:applicationContext.xml org.s ...

  3. 在 Spring Boot 中使用 Spring AOP 和 AspectJ 来测量方法的执行时间

    原文链接:https://dzone.com/articles/logging-average-method-execution-times-via-aspectj 作者:Murat Derman 译 ...

  4. Spring Boot中使用Spring Data JPA示例

    JPA是Java Persistence API的简称,是sun公司早期推出的Java持久层规范,目前实现JPA规范的主流框架有Hibernate.OpenJPA等.Hibernate框架是当前较为流 ...

  5. spring boot中配置虚拟路径,用来映射显示图片

    增加配置,继承 WebMvcConfigurerAdapter,如下: package com.wm.mogu_picture.config;import org.springframework.be ...

  6. 在Spring Boot中加载初始化数据

    文章目录 依赖条件 data.sql文件 schema.sql 文件 @sql注解 @SqlConfig 注解 在Spring Boot中加载初始化数据 在Spring Boot中,Spring Bo ...

  7. 第 4-4 课:Spring Boot 中使⽤ Cache 缓存的使⽤

    我们知道绝⼤多数的⽹站/系统,最先遇到的⼀个性能瓶颈就是数据库,使⽤缓存做数据库的前置缓存,可以 ⾮常有效地降低数据库的压⼒,从⽽提升整个系统的响应效率和并发量. 以往使⽤缓存时,通常创建好缓存⼯具类 ...

  8. springboot 访问html_Spring Boot中使用Spring Security进行安全控制

    我们在编写Web应用时,经常需要对页面做一些安全控制,比如:对于没有访问权限的用户需要转到登录表单页面.要实现访问控制的方法多种多样,可以通过Aop.拦截器实现,也可以通过框架实现(如:Apache ...

  9. 使用Spring Security在Spring Boot中进行缓存

    在这篇文章中,我想分享一下O&B的一个团队的经验教训. 他们正在使用带有Spring Security的Spring Boot. 默认情况下,Spring Security保护的所有内容都将通 ...

最新文章

  1. 单文件浏览器_图文并茂深度解析浏览器渲染原理,包看懂超值得收藏
  2. mysql 获取姓名首字母_MySQL取姓名的首字母
  3. Python基础06 循环
  4. 如何判断当前的SAP Spartacus已经运行在SSR模式,而不是PWA模式下了
  5. 如何设置坐标原点值_氨气检测仪电化学原理及报警值如何设置
  6. ant指定servlet版本_[转载]程序开发常见错误
  7. 微课|玩转Python轻松过二级(2.1.3节):字符串与字节串简介
  8. 业余草最新热门博客推荐
  9. 双舵轮AGV轨迹跟踪Pure Pursuit算法模型分析、python代码实现
  10. 单片机、嵌入式ARM学习网站推荐(多年的积累)
  11. python将电视剧按收视率进行排序_2019电视剧收视率排行榜
  12. onedrive 添加到本地硬盘_Win10系统OneDrive映射到本地磁盘的解决设置技巧
  13. 【Mobile】CTA认证
  14. hue oozie spark:GC overhead limt exceed
  15. 【Android】kotlin语法学习
  16. 健康——每日饮水量建议
  17. RHEL iSCSI
  18. 巴别塔合约作战终端开发日记4——后端效率优化
  19. 基于React Native的移动平台研发实践分享
  20. 快手616品质购物节电商报告来了!24位达人带货破亿,新一代带货王诞生!

热门文章

  1. HDOJ 1494 跑跑卡丁车
  2. 成员变量的声明位置引起编译错误
  3. 监控和剖析数据库操作P6Spy,SQL Profiler,SQL 使用简介
  4. UDT源码剖析(六):UDT::socket()过程代码注释
  5. 常见单元测试工具介绍
  6. 有人知道 I3C 吗?
  7. Git 忽略一些文件的提交
  8. python按位翻转_Python成为专业人士笔记-位操作符
  9. LeetCode 963. 最小面积矩形 II
  10. LeetCode 1641. 统计字典序元音字符串的数目(DP)