- ①Security入门体验
- ②Security自定义账号密码验证+thymeleaf登录案例(附带网页案例
- ③Security+验证码登录案例(附带网页案例)
- ④Security+jwt 实现无状态认证,前后端分离(附带网页案例))
- ⑤Security+jwt 短信认证登录,前后端分离(附带网页案例)
- ⑥Security+oauth2 授权服务器(附带网页案例)
文章目录
- Security系列教程
- 简介
- 1. 环境
- 2. 开启或关闭Spring Security安全认证
- 3. 配置表单认证登录
- 4. 效果演示
- 5. 源码分享
简介
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。
- 本系列文章以实战讲解为主,帮助开发者快速入门并应用到实际开发中。
- springboot 版本为
org.springframework.boot spring-boot-starter-parent 2.5.3
- 引入security依赖
org.springframework.boot spring-boot-starter-security
- yml 配置端口
server: port: 99992. 开启或关闭Spring Security安全认证
- 当我们引入了spring-boot-starter-security依赖的时候,项目就会默认开启安全认证。
- 若想关闭认证,把security.basic.enabled设为false即可。
security:
basic:
# 默认开启,无需配置,关闭设为false即可
enabled: true
3. 配置表单认证登录
- 开启Spring Security的认证功能
- WebSecurityConfig.java
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 表单方式
http.formLogin()
.and()
// 授权配置
.authorizeRequests()
// 所有请求
.anyRequest()
// 都需要认证
.authenticated();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
// 用户名
.withUser("admin")
// 密码
.password(passwordEncoder().encode("123456"))
// 角色
.roles("ADMIN");
}
@Bean
public PasswordEncoder passwordEncoder() {
// 使用BCrypt加密密码
return new BCryptPasswordEncoder();
}
}
- @EnableWebSecurity 开启Security
- @EnableGlobalMethodSecurity(prePostEnabled = true) 开启Security的注解功能
- 编写测试接口
@RestController
public class IndexController {
@GetMapping("/")
public String index() {
return "请求成功";
}
@GetMapping("/get")
public String get() {
return "神秘代码9527";
}
}
- 启动项目
- 浏览器输入localhost:9999/
- 账号/密码为我们上一步配置的 admin/123456
- 登录成功
本系列项目已收录
Springboot、SpringCloud全家桶教程+源码,各种常用框架使用案例都有哦,具备完善的文档,致力于让开发者快速搭建基础环境并让应用跑起来,并提供丰富的使用示例供使用者参考,快来看看吧。
- 项目源码github地址
- 项目源码国内gitee地址



