Spinrg Security 浅谈
最近也是学习了 Spring Security ,顺便放出来一波自己整理的知识点 希望大家少走弯路
什么是 Spring Security呢?
贴一下官网的定义:Spring Security is a framework that provides authentication, authorization, and protection against common attacks. With first class support for securing both imperative and reactive applications, it is the de-facto standard for securing Spring-based applications.
简单来说:Spring Security 是一个框架,可提供针对常见攻击的身份验证、授权和保护。它为保护命令式和反应式应用程序提供了一流的支持,是保护基于 Spring 的应用程序的事实标准。
那么什么是身份认证和授权呢?
身份认证:
- 身份认证是验证
谁正在访问系统资源
,判断用户是否为合法用户。认证用户的常见方式是要求用户输入用户名和密码。
授权:
- 用户进行身份认证后,系统会控制
谁能访问哪些资源
,这个过程叫做授权。用户无法访问没有权限的资源。
首先说一下 Spring Security 的身份认证
1.1、创建Spring Boot项目
项目名:security-demo
JDK:17
SpringBoot:3.2.0(依赖了Spring Security 6.2.0)
Dependencies:Spring Web、Spring Security、Thymeleaf
1.2、创建IndexController
package com.atguigu.securitydemo.controller;
@Controller
public class IndexController {
@GetMapping("/")
public String index() {
return "index";
}
}
1.3、创建index.html
在路径resources/templates中创建index.html
<html xmlns:th="https://www.thymeleaf.org">
<head>
<title>Hello Security!</title>
</head>
<body>
<h1>Hello Security</h1>
<!--通过使用@{/logout},Thymeleaf将自动处理生成正确的URL,以适应当前的上下文路径。
这样,无论应用程序部署在哪个上下文路径下,生成的URL都能正确地指向注销功能。-->
<a th:href="@{/logout}">Log Out</a>
</body>
</html>
1.4、启动项目测试Controller
浏览器中访问:http://localhost:8080/
浏览器自动跳转到登录页面:http://localhost:8080/login
输入用户名:user
输入密码:在控制台的启动日志中查找初始的默认密码
点击"Sign in"进行登录,浏览器就跳转到了index页面
这样一个Spring Security 就快速启动好啦
通过使用@{/logout},Thymeleaf将自动处理生成正确的URL,以适应当前的上下文路径。这样,无论应用程序部署在哪个上下文路径下,生成的URL都能正确地指向注销功能。
例如:如果我们在配置文件中添加如下内容
server.servlet.context-path=/demo
Spring Security 默认做了哪些事情呢?
- 保护应用程序URL,要求对应用程序的任何交互进行身份验证。
- 程序启动时生成一个默认用户“user”。
- 生成一个默认的随机密码,并将此密码记录在控制台上。
- 生成默认的登录表单和注销页面。
- 提供基于表单的登录和注销流程。
- 对于Web请求,重定向到登录页面;
- 对于服务请求,返回401未经授权。
- 处理跨站请求伪造(CSRF)攻击。
- 处理会话劫持攻击。
- 写入Strict-Transport-Security以确保HTTPS。
- 写入X-Content-Type-Options以处理嗅探攻击。
- 写入Cache Control头来保护经过身份验证的资源。
- 写入X-Frame-Options以处理点击劫持攻击。
既然它默认帮我们做了这些事情,那么它到底是怎么做到的呢?
底层原理浅析:
Spring Security之所以默认帮助我们做了那么多事情,它的底层原理是传统的Servlet过滤器
当一个 http 请求到来时,经历的过程如下:
因此我们可以在过滤器中对请求进行修改或增强
在复杂的业务处理中不可能只有一个过滤器,因此 FilterChainProxy 诞生了。它是 Spring Security 中提供的一个特殊的 Filter ,它允许通过 SecurityFilterChain 将过滤器的工作委托给多个 Bean Filter 实例,它的组成如下:![请添加图片描述](https://i-blog.csdnimg.cn/direct/986df5dda1854c3aa4f836fef184cdfb.png)
SecurityFilterChain 被 FilterChainProxy 使用,负责查找当前的请求需要执行的Security Filter列表
可以有多个SecurityFilterChain的配置,FilterChainProxy决定使用哪个SecurityFilterChain。如果请求的URL是/api/messages/,它首先匹配SecurityFilterChain0的模式/api/**,因此只调用SecurityFilterChain 0。假设没有其他SecurityFilterChain实例匹配,那么将调用SecurityFilterChain n。
SecurityFilterChain 接口的实现,默认加载了16 个 Filter
Spring Security 的基本运行就是建立在这16个基本的 Filter 上,一些基本的使用代码大家可以移步到我的仓库去看一下每一次 commit ,每次 commit 的注释十分清晰,大家可以根据具体的代码进行各个功能的初步学习