Spring Boot如何使用Spring Security进行安全控制

 更新时间:2017年04月27日 16:34:22   作者:Joker_Ye  
要实现访问控制的方法多种多样,可以通过Aop、拦截器实现,也可以通过框架实现,本文将具体介绍在Spring Boot中如何使用Spring Security进行安全控制。

我们在编写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";
  }

}
  1. / :映射到index.html
  2. /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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Spring Boot构建系统安全层的步骤

    Spring Boot构建系统安全层的步骤

    这篇文章主要介绍了Spring Boot构建系统安全层的步骤,帮助大家更好的理解和学习使用Spring Boot框架,感兴趣的朋友可以了解下
    2021-04-04
  • Java轻松使用工具类实现获取wav时间长度

    Java轻松使用工具类实现获取wav时间长度

    在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用工具类来获取一个wav文件的时间长度,感兴趣的同学继续往下阅读吧
    2021-10-10
  • Java实现添加条形码到PDF表格的方法详解

    Java实现添加条形码到PDF表格的方法详解

    条码的应用已深入生活和工作的方方面面。本文以操作PDF文件为例,介绍如何利用Java语言在编辑表格时,向单元格中添加条形码,感兴趣的可以学习一下
    2022-06-06
  • SpringBoot项目中的多数据源支持的方法

    SpringBoot项目中的多数据源支持的方法

    本篇文章主要介绍了SpringBoot项目中的多数据源支持的方法,主要介绍在SpringBoot项目中利用SpringDataJpa技术如何支持多个数据库的数据源,有兴趣的可以了解一下
    2017-10-10
  • Java实现最小高度树

    Java实现最小高度树

    本文主要介绍了Java实现最小高度树,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-04-04
  • Idea中Springboot热部署无效问题解决

    Idea中Springboot热部署无效问题解决

    这篇文章主要介绍了Idea中Springboot热部署无效问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • java  线程详解及线程与进程的区别

    java 线程详解及线程与进程的区别

    这篇文章主要介绍了java 线程详解及线程与进程的区别的相关资料,网上关于java 线程的资料很多,对于进程的资料很是,这里就整理下,需要的朋友可以参考下
    2017-01-01
  • SpringBoot整合redis使用缓存注解详解

    SpringBoot整合redis使用缓存注解详解

    这篇文章主要介绍了SpringBoot整合redis使用缓存注解详解,@Cacheable在方法执行前判断对应缓存是否存在,如果存在直接返回缓存结果,否者执行方法将结果缓存,适用于查询类,需要的朋友可以参考下
    2024-01-01
  • Java 和 Javascript 的 Date 与 .Net 的 DateTime 之间的相互转换

    Java 和 Javascript 的 Date 与 .Net 的 DateTime 之间的相互转换

    这篇文章主要介绍了Java 和 Javascript 的 Date 与 .Net 的 DateTime 之间的相互转换的相关资料,非常不错具有参考借鉴价值,需要的朋友可以参考下
    2016-06-06
  • 快速搭建Spring Boot+MyBatis的项目IDEA(附源码下载)

    快速搭建Spring Boot+MyBatis的项目IDEA(附源码下载)

    这篇文章主要介绍了快速搭建Spring Boot+MyBatis的项目IDEA(附源码下载),本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12

最新评论