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

发布时间 - 2026-01-11 00:52:35    点击率:

我们在编写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  # security  # springboot  # security4  # 安全  # SpringBoot + Spring Security 基本使用及个性化登录配置详解  # 详解如何在spring boot中使用spring security防止CSRF攻击  # SpringBoot+Vue前后端分离  # 使用SpringSecurity完美处理权限问题的解决方法  # Spring Boot中使用 Spring Security 构建权限系统的示例代码  # 详解Spring Boot 使用Spring security 集成CAS  # Spring Boot(四)之使用JWT和Spring Security保护REST API  # Spring Security 在 Spring Boot 中的使用详解【集中式】  # 可以通过  # 就可以  # 转到  # 可以看到  # 如何使用  # 跳转到  # 访问权限  # 重定向  # 完成了  # 在这里  # 相关内容  # 在这  # 不需要  # 没有任何  # 可以用  # 其他的  # 我们可以  # 将对  # 重写  # 多种多样 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: iOS发送验证码倒计时应用  湖南网站制作公司,湖南上善若水科技有限公司做什么的?  昵图网官方站入口 昵图网素材图库官网入口  Python自然语言搜索引擎项目教程_倒排索引查询优化案例  如何制作公司的网站链接,公司想做一个网站,一般需要花多少钱?  Laravel如何实现用户密码重置功能?(完整流程代码)  如何快速搭建高效WAP手机网站?  黑客如何通过漏洞一步步攻陷网站服务器?  Laravel distinct去重查询_Laravel Eloquent去重方法  如何自定义safari浏览器工具栏?个性化设置safari浏览器界面教程【技巧】  ,网页ppt怎么弄成自己的ppt?  如何在万网开始建站?分步指南解析  PHP怎么接收前端传的文件路径_处理文件路径参数接收方法【汇总】  详解Huffman编码算法之Java实现  大连 网站制作,大连天途有线官网?  如何用腾讯建站主机快速创建免费网站?  Laravel如何使用模型观察者?(Observer代码示例)  Laravel DB事务怎么使用_Laravel数据库事务回滚操作  Laravel如何使用Livewire构建动态组件?(入门代码)  Laravel如何构建RESTful API_Laravel标准化API接口开发指南  Laravel如何使用Eloquent ORM进行数据库操作?(CRUD示例)  高端建站三要素:定制模板、企业官网与响应式设计优化  如何打造高效商业网站?建站目的决定转化率  如何用虚拟主机快速搭建网站?详细步骤解析  深入理解Android中的xmlns:tools属性  东莞专业网站制作公司有哪些,东莞招聘网站哪个好?  Laravel如何与Inertia.js和Vue/React构建现代单页应用  如何自己制作一个网站链接,如何制作一个企业网站,建设网站的基本步骤有哪些?  Laravel队列由Redis驱动怎么配置_Laravel Redis队列使用教程  googleplay官方入口在哪里_Google Play官方商店快速入口指南  如何自定义建站之星网站的导航菜单样式?  ,怎么在广州志愿者网站注册?  Python面向对象测试方法_mock解析【教程】  google浏览器怎么清理缓存_谷歌浏览器清除缓存加速详细步骤  今日头条AI怎样推荐抢票工具_今日头条AI抢票工具推荐算法与筛选【技巧】  千库网官网入口推荐 千库网设计创意平台入口  香港服务器网站推广:SEO优化与外贸独立站搭建策略  如何在七牛云存储上搭建网站并设置自定义域名?  JS弹性运动实现方法分析  微信小程序 scroll-view组件实现列表页实例代码  Laravel Eloquent关联是什么_Laravel模型一对一与一对多关系精讲  微信小程序 HTTPS报错整理常见问题及解决方案  LinuxShell函数封装方法_脚本复用设计思路【教程】  Laravel怎么集成Vue.js_Laravel Mix配置Vue开发环境  黑客如何利用漏洞与弱口令入侵网站服务器?  Laravel如何监控和管理失败的队列任务_Laravel失败任务处理与监控  mc皮肤壁纸制作器,苹果平板怎么设置自己想要的壁纸我的世界?  Laravel如何实现一对一模型关联?(Eloquent示例)  清除minerd进程的简单方法  Android 常见的图片加载框架详细介绍