# springboot_security **Repository Path**: qiangzhouliang_admin/springboot_security ## Basic Information - **Project Name**: springboot_security - **Description**: springboot_security 学习代码 - **Primary Language**: Java - **License**: AGPL-3.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2021-08-30 - **Last Updated**: 2024-08-09 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 1 SpringSecurity(安全) ## 1.1 SpringSecurity简介 **Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。**它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。 > 核心功能: - 认证Authentication (你是谁) - 授权Authorization(你能干什么) - 攻击防护 (防止伪造身份) > 常用类 - WebSecurityConfigurerAdapter:自定义Security策略 - AuthenticationManagerBuilder:自定义认证策略 - @EnableWebSecurity:开启WebSecurity模式 > 官网 `https://spring.io/projects/spring-security` 帮助文档:`https://docs.spring.io/spring-security/site/docs/current/reference/html5/` ## 1.2 入门程序 1. 新建`springboot-security项目` ![在这里插入图片描述](https://img-blog.csdnimg.cn/74856a1d59024924aee26b672363eabf.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5ZaE6Imv55qE54ix5b-D6K-d,size_20,color_FFFFFF,t_70,g_se,x_16) 2. 导入依赖 pom.xml ```xml org.springframework.boot spring-boot-starter-security org.thymeleaf thymeleaf-spring5 org.thymeleaf.extras thymeleaf-extras-java8time org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-devtools runtime true org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test ``` 3. 编写配置文件 yml ``` spring: thymeleaf: cache: false # 关闭缓存 ``` 4. 编写测试 controller:RouterController ```java package com.swan.springboot_security.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; /** * @ClassName RouterController * @Description 路由跳转页面controller * @Author qzl * @Date 2021/8/30 9:37 上午 **/ @Controller public class RouterController { @RequestMapping({"/","/index"}) public String index(){ return "index"; } @RequestMapping("toLogin") public String toLogin(){ return "views/login"; } @RequestMapping("/level1/{id}") public String level1(@PathVariable("id") int id){ return "views/level1/"+id; } @RequestMapping("/level2/{id}") public String level2(@PathVariable("id") int id){ return "views/level2/"+id; } @RequestMapping("/level3/{id}") public String level3(@PathVariable("id") int id){ return "views/level3/"+id; } } ``` 5. 编写配置文件`SecurityConfig.java`,进行认证和授权 ```java package com.swan.springboot_security.config; 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.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import java.util.Arrays; /** * @ClassName SecurityConfig * @Description 安全配置 * @Author qzl * @Date 2021/8/30 9:53 上午 **/ @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // 授权的方法 @Override protected void configure(HttpSecurity http) throws Exception { // 首页所有人可以访问,功能页只有对应有权限的人才能访问 // 请求授权的规则 http.authorizeRequests() .antMatchers(Arrays.asList("/","/index").toString()).permitAll() // 所有人可以访问 .antMatchers("/level1/**").hasAnyRole("vip1") // 需要有权限才能访问 .antMatchers("/level2/**").hasAnyRole("vip2") .antMatchers("/level3/**").hasAnyRole("vip3"); // 没有权限默认会跳转到登录页面,需要开启登录的页面 //toLogin //定制登录页 .loginPage("/toLogin") //.loginProcessingUrl("/login") 登录认证的地址 http.formLogin().loginPage("/toLogin") .usernameParameter("user").passwordParameter("pwd") .loginProcessingUrl("/login"); //注销:开启了注销功能,正常注销后,跳到首页 //防止网站攻击:get http.csrf().disable(); // 关闭csrf验证 http.logout().logoutSuccessUrl("/"); //开启记住我功能 cookie,默认保存两周,自定义接收前端的参数 http.rememberMe().rememberMeParameter("remember"); } //认证的方法 在 springboot 2.1.x 可以直接使用 // 密码编码: passwordEncoder // 在Spring Secutiry 5.0+ 新增了很多的加密方法 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //这些数据正常应该从数据库中读 //从内存中认证 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("swan").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3") .and() .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3") .and() .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1"); } } ``` 6. 运行进入首页 ![在这里插入图片描述](https://img-blog.csdnimg.cn/51c10ca920d74439aaa923f60dc814dc.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5ZaE6Imv55qE54ix5b-D6K-d,size_20,color_FFFFFF,t_70,g_se,x_16) ## 1.3 springSecurity 整合 thymeleaf 在上面的项目中操作 1. 导包 ```xml org.thymeleaf.extras thymeleaf-extras-springsecurity4 3.0.4.RELEASE org.thymeleaf.extras thymeleaf-extras-springsecurity5 3.0.4.RELEASE ``` 2. 判断登录状态修改首页右上角信息 - 导入命名空间 ```html xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5" xmlns:sec="http://www.thymeleaf.org/extras/spring-security" ``` - 修改html ```html ``` 3. 控制有权限才显示首页菜单-首页菜单控制 ```html
```