第一章 Spring Security快速入门
官方文档:
https://docs.spring.io/spring-security/reference/index.html
功能:
- 身份认证(authentication)
- 授权(authorization)
- 防御常见攻击(protection against common attacks)
身份认证:
- 身份认证是验证
谁正在访问系统资源,判断用户是否为合法用户。认证用户的常见方式是要求用户输入用户名和密码。
授权:
- 用户进行身份认证后,系统会控制
谁能访问哪些资源,这个过程叫做授权。用户无法访问没有权限的资源。
防御常见攻击:
- CSRF
- HTTP Headers
- HTTP Requests
1、身份认证(authentication)
官方代码示例:GitHub - spring-projects/spring-security-samples
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页面
1.5、注意事项
1.5.1、@{/logout}的作
通过使用@{/logout},Thymeleaf将自动处理生成正确的URL,以适应当前的上下文路径。这样,无论应用程序部署在哪个上下文路径下,生成的URL都能正确地指向注销功能。
例如:如果我们在配置文件中添加如下内容
server.servlet.context-path=/demo
那么@{/logout}可以自动处理url为正确的相对路径
但是如果是普通的/logout,路径就会不正确