【SpringBoot】Spring Security
官网:
https://docs.spring.io/spring-security/site/docs/5.3.2.RELEASE/reference/html5/
Spring Security provides comprehensive support for authentication, authorization, and protection against common exploits. It also provides integration with other libraries to simplify its usage.
https://github.com/spring-projects/spring-security/tree/5.3.2.RELEASE/samples
https://docs.spring.io/spring-security/site/docs/5.3.4.RELEASE/reference/html5/#exploits 章节5.2
小马哥视频: springBoot security视频
一、Demo
1、默认弹框提示
pom.xml 中的 Spring Security 依赖:
只要加入依赖,项目的所有接口都会被自动保护起来;登录弹框
密码出处:在启动时,控制台打印(用户名user)
Using generated security password: 8e557245-73e2-4286-969a-ff57fe326336
背后的源码:SecurityProperties.java
2、定制登录用户名/密码三种方式
1)在 application.properties 中进行配置
spring.security.user.name=tester
spring.security.user.password=123
2)通过Java代码指定
从 Spring5 开始,强制要求密码要加密,如果非不想加密,可以使用一个过期的 PasswordEncoder 的实例 NoOpPasswordEncoder,但是不建议这么做,毕竟不安全。
Spring Security 中提供了 BCryptPasswordEncoder 密码编码工具,可以非常方便的实现密码的加密加盐,相同明文加密出来的结果总是不同,这样就不需要用户去额外保存盐的字段了,这一点比 Shiro 要方便很多。
3、登录配置(派生WebSecurityConfigurerAdapter)
如果是前后端分离开发的话,登录成功后返回 JSON 即可,同理,failureHandler 方法中配置登录失败的回调,logoutSuccessHandler 中则配置注销成功的回调。
4、忽略拦截
二、关键知识点-- 核心类
1、抽象类:WebSecurityConfigurerAdapter
HTTP安全响应头:
1、Security Default Header
Spring Security provides a default set of security related HTTP response headers to provide secure defaults.
The default for Spring Security is to include the following headers:
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000 ; includeSubDomains // only added on HTTPS requests
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
2、Cache-Control
Spring Security’s default is to disable caching to protect user’s content.
If a user authenticates to view sensitive information and then logs out, we don’t want a malicious user to be able to click the back button to view the sensitive information
Default Cache Control HTTP Response Headers
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)