Spring Security基础:快速搭建安全认证系统
——给零基础新手的实践入门教程
一、开篇:什么是Spring Security?它能做什么?

大家好!今天我们来一起学习 Spring Security,这是一个非常强大的框架,专门用来为我们的Java Web项目添加“安全机制”。
简单理解:
想象你有一栋房子,门上没有锁。任何人都能随意进出,多危险啊!而 Spring Security 就像是一个智能门禁系统,它可以帮你:
- 控制谁可以访问你的网站
- 判断用户是否登录
- 不同身份(如管理员/普通用户)能访问不同的区域
应用场景举例:
- 用户注册和登录功能
- 后台系统权限分级(如只允许管理员访问)
- 接口访问令牌验证(类似微信接口的安全校验)
二、环境准备:从0开始搭建开发环境

我们使用 Spring Boot + Spring Security 快速搭建一个简单的安全系统。
步骤1:安装JDK(Java 开发工具包)
推荐版本:JDK 17 或更高
下载地址:https://www.oracle.com/java/technologies/downloads/
💡 验证是否安装成功:打开命令行输入
java -version
步骤2:安装IDE(推荐IntelliJ IDEA)
下载社区版:https://www.jetbrains.com/idea/download/
步骤3:创建Spring Boot项目
前往 Spring Initializr 创建新项目:
- Project: Maven
- Language: Java
- Spring Boot Version: 最新版即可
- Group: com.example
- Artifact: securitydemo
- Dependencies 添加:
- Spring Web
- Spring Security
然后点击 Generate 下载项目压缩包。
解压并导入 IntelliJ IDEA 中。
三、核心概念讲解:几个必须知道的关键术语

为了让新手更容易理解,我将通过类比的方式来介绍这些概念。
| 概念名称 | 类比说明 | 作用 |
|---|---|---|
| Authentication(认证) | 身份识别卡 | 验证你是谁 |
| Authorization(授权) | 房间钥匙权限 | 决定你能访问什么资源 |
| UserDetailsService | 存储所有员工资料的档案库 | 获取用户信息用于认证 |
| PasswordEncoder | 加密文件夹 | 安全存储密码 |
| SecurityConfig | 门禁规则配置表 | 定义安全策略 |
四、实战项目:一步一步搭建登录认证系统
接下来,我们将创建一个简单的登录系统,允许用户名为“admin”、密码为“123456”的用户访问 /hello 页面。
第一步:添加登录页面
在 src/main/resources/templates 目录下创建一个 login.html 文件(如果没有templates目录就新建)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Login</title>
</head>
<body>
<h2>Login Page</h2>
<form action="/login" method="post">
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required><br/>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required><br/>
<button type="submit">登录</button>
</form>
</body>
</html>
第二步:创建一个简单的Controller
编辑文件:src/main/java/com/example/securitydemo/controller/HomeController.java
package com.example.securitydemo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@RestController
public class HomeController {
@GetMapping("/login")
public ModelAndView loginPage() {
return new ModelAndView("login");
}
@GetMapping("/hello")
public String hello() {
return "欢迎来到安全的世界!";
}
}
第三步:配置Security规则
创建文件:src/main/java/com/example/securitydemo/config/SecurityConfig.java
package com.example.securitydemo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
// 密码编码器
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// 设置用户账户(内存中)
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("123456")) // 存储加密后的密码
.roles("USER"); // 分配角色
}
// 设置访问控制规则
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> {
auth.requestMatchers("/hello").authenticated(); // /hello需要登录才能访问
auth.anyRequest().permitAll(); // 其他请求不需要登录
})
.formLogin(form -> form
.loginPage("/login") // 自定义登录页路径
.defaultSuccessUrl("/hello", true) // 登录成功跳转
.permitAll()
)
.logout(logout -> logout.permitAll()); // 支持退出
}
}
⚠️ 注意:以上代码中的
protected void方法名与参数可能会因Spring Boot版本不同略有差异,建议参考官方文档或自动补全提示调整。
第四步:运行测试
- 执行主类:右键点击
com.example.securitydemo.SecuritydemoApplication.java→ Run Application。 - 打开浏览器,访问:http://localhost:8080/hello
- 输入用户名
admin,密码123456 - 成功登录后看到:“欢迎来到安全的世界!”
🎉 完成啦!
五、常见问题解答(FAQ)
❓Q1:为什么不能直接写明文密码?
因为明文密码一旦被泄露,就会被别人轻易利用。所以我们用
BCryptPasswordEncoder对密码进行加密处理。
❓Q2:我的登录页面不显示怎么办?
请检查模板目录是否正确放置在
resources/templates中,并且使用了 Thymeleaf 或其他视图解析器。Spring Boot默认支持Thymeleaf,如果你没添加,请添加依赖。
Maven添加Thymeleaf依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
❓Q3:为什么登录后跳不到/hello?
可能是
.defaultSuccessUrl()没有设置正确。确保拼写无误,并且设置了第二个参数为true,以强制跳转。
六、学习建议:下一步怎么学?
你现在已掌握了Spring Security最基础的能力,下面是一些进阶方向推荐:
✅ 建议路线:
- 学习使用数据库做用户管理(如MySQL + JPA)
- 替换内存用户为数据库用户
- 实现基于角色的权限控制
- 如ROLE_ADMIN 和 ROLE_USER 访问不同接口
- 学习JWT(Json Web Token)
- 构建前后端分离项目的认证机制
- 集成OAuth2第三方登录
- 实现如“微信登录”、“QQ登录”
- 深入学习CSRF防护、Session管理等高级安全措施
📚 推荐资源:
- 官方文档:https://docs.spring.io/spring-security/site/docs/current/reference/html5/
- GitHub案例合集:搜索关键词 “spring security demo”
结语
恭喜你完成了第一个基于Spring Security的安全认证项目!
只要你肯动手敲代码,你会发现 Spring Security 并不像听起来那么复杂。记住一句话:
安全,就是保护自己的数字世界,从每一个小步骤开始。
继续加油,未来你也能做出企业级安全系统!
📌 如需完整示例代码,可访问 GitHub 示例仓库(你可以自行上传到个人账号后分享)
如你喜欢本教程,欢迎点赞、收藏、转发给更多小伙伴 👏

评论 0