SpringBoot3-11.场景整合-Web 安全-Spring Security

2024年01月08日 11:41 · 阅读(107) ·

安全框架

Apache Shiro
Spring Security
● 自研:Filter

权限模型

1.RBAC(Role Based Access Controll)

  • 用户(t_user)
    • id,username,password,xxx
    • 1,zhangsan
    • 2,lisi
  • 用户_角色(t_user_role)【N 对 N 关系需要中间表】
    • zhangsan, admin
    • zhangsan,common_user
    • lisi, hr
    • lisi, common_user
  • 角色(t_role)
    • id,role_name
    • admin
    • hr
    • common_user
  • 角色_权限(t_role_perm)
    • admin, 文件r
    • admin, 文件w
    • admin, 文件执行
    • admin, 订单query,create,xxx
    • hr, 文件r
  • 权限(t_permission)
    • id,perm_id
    • 文件 r,w,x
    • 订单 query,create,xxx

2.ACL(Access Controll List)

  • 用户(t_user)
    • zhangsan
    • lisi
  • 用户_权限(t_user_perm)
    • zhangsan,文件 r
    • zhangsan,文件 x
    • zhangsan,订单 query
  • 权限(t_permission)
    • id,perm_id
    • 文件 r,w,x
    • 订单 query,create,xxx

安全架构

1.认证:Authentication

who are you?
登录系统,用户系统

2.授权:Authorization

what are you allowed to do?
权限管理,用户授权

3.攻击防护

● XSS(Cross-site scripting)——跨站脚本攻击
● CSRF(Cross-site request forgery)——跨站请求伪造
● CORS(Cross-Origin Resource Sharing)——跨域资源共享攻击
● SQL 注入
● …

Spring Security 原理

1.过滤器链架构

Spring Security 利用 FilterChainProxy 封装一系列拦截器链,实现各种安全拦截功能
Servlet三大组件:Servlet、Filter、Listener

2.FilterChainProxy

3.SecurityFilterChain

实战

新建项目-boot3-13-security

  • 新建模块 boot3-13-security

  • 创建模块

名称 boot3-13-security
位置 D:\Study-Java\2023\SpringBoot3-Study
语言 Java
构建系统 Maven
JDK 版本:17
供应商:Eclipse Temurin(AdoptOpenJDK HotSpot)17.0.8
位置:C:\Users\Administrator.jdks\temurin-17.0.8
主 ID com.atguigu
工件 ID boot3-13-security
软件包名称 com.atguigu.boot3.security
  • SpringBoot 3.2.0
  • 依赖项目
  1. Developer Tools
  2. -- Lombok
  3. Web
  4. -- Spring Web
  5. Template Engines
  6. -- Thymeleaf
  7. Security
  8. -- Spring Security

资源目录

  1. pom.xml
  2. ├─src
  3. ├─main
  4. ├─java
  5. └─com
  6. └─atguigu
  7. └─boot3
  8. └─security
  9. Boot313SecurityApplication.java
  10. ├─cofig
  11. AppSecurityConfiguration.java
  12. └─controller
  13. HelloController.java
  14. LoginController.java
  15. └─resources
  16. application.properties
  17. ├─static
  18. └─templates
  19. index.html
  20. login.html

1.引入依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-security</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-web</artifactId>
  13. </dependency>
  14. <dependency>
  15. <groupId>org.thymeleaf.extras</groupId>
  16. <artifactId>thymeleaf-extras-springsecurity6</artifactId>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.projectlombok</groupId>
  20. <artifactId>lombok</artifactId>
  21. <optional>true</optional>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-test</artifactId>
  26. <scope>test</scope>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.security</groupId>
  30. <artifactId>spring-security-test</artifactId>
  31. <scope>test</scope>
  32. </dependency>
  33. </dependencies>

2.页面

首页-index.html

  1. <h1>Welcome To Spring Security!</h1>
  2. <a th:href="@{/hello}">hello</a><br />
  3. <a th:href="@{/world}">world</a>

登录页-login.html

  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
  3. <head>
  4. <title>Spring Security Example</title>
  5. </head>
  6. <body>
  7. <div th:if="${param.error}">Invalid username and password.</div>
  8. <div th:if="${param.logout}">You have been logged out.</div>
  9. <form th:action="@{/login}" method="post">
  10. <div>
  11. <label> User Name : <input type="text" name="username" /> </label>
  12. </div>
  13. <div>
  14. <label> Password: <input type="password" name="password" /> </label>
  15. </div>
  16. <div><input type="submit" value="Sign In" /></div>
  17. </form>
  18. </body>
  19. </html>

3.控制器

Login

  1. package com.atguigu.boot3.security.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. @Controller
  5. public class LoginController {
  6. @GetMapping("/login")
  7. public String loginPage() {
  8. return "login";
  9. }
  10. }

Hello

  1. package com.atguigu.boot3.security.controller;
  2. import org.springframework.security.access.prepost.PreAuthorize;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @RestController
  6. public class HelloController {
  7. @GetMapping("/hello")
  8. public String hello() {
  9. return "Hello Spring Security!";
  10. }
  11. @PreAuthorize("hasAuthority('world_exec')")
  12. @GetMapping("/world")
  13. public String world() {
  14. return "Hello Spring Security!";
  15. }
  16. }

4.配置类

  1. package com.atguigu.boot3.security.cofig;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
  5. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  6. import org.springframework.security.core.userdetails.User;
  7. import org.springframework.security.core.userdetails.UserDetails;
  8. import org.springframework.security.core.userdetails.UserDetailsService;
  9. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  10. import org.springframework.security.crypto.password.PasswordEncoder;
  11. import org.springframework.security.provisioning.InMemoryUserDetailsManager;
  12. import org.springframework.security.web.SecurityFilterChain;
  13. /**
  14. * 配置类
  15. * 1. 自定义请求授权规则:http.authorizeHttpRequests
  16. * 2. 自定义登录规则:http.formLogin
  17. * 3. 自定义用户信息查询规则:UserDetailsService
  18. * 4. 开启方法级别的精确权限控制:EnableMethodSecurity
  19. */
  20. @Configuration
  21. @EnableMethodSecurity
  22. public class AppSecurityConfiguration {
  23. /**
  24. * 自定义请求授权规则
  25. * @param http HttpSecurity
  26. * @return 请求授权规则
  27. * @throws Exception 异常信息
  28. */
  29. @Bean
  30. SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  31. //请求授权
  32. http.authorizeHttpRequests(registry -> {
  33. registry.requestMatchers("/").permitAll()//1. 首页无需登录
  34. .anyRequest().authenticated();//2. 剩下的任意请求都需要认证(登录)
  35. });
  36. //表单登录
  37. //3. 表单登录功能:开启默认表单登录功能,Spring Security 提供默认登录页
  38. http.formLogin(formLogin -> {
  39. //自定义登录页位置,并且所有人都能访问
  40. formLogin.loginPage("/login").permitAll();
  41. });
  42. return http.build();
  43. }
  44. /**
  45. * 自定义登录规则
  46. * @param passwordEncoder 密码加密器
  47. * @return 用户详情信息
  48. */
  49. @Bean
  50. UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
  51. //用户信息
  52. UserDetails zhangsan = User.withUsername("zhangsan")
  53. .password(passwordEncoder.encode("123456"))
  54. .roles("admin", "hr")
  55. .authorities("file_read", "file_write")
  56. .build();
  57. UserDetails lisi = User.withUsername("lishi")
  58. .password(passwordEncoder.encode("123456"))
  59. .roles("hr")
  60. .authorities("file_read")
  61. .build();
  62. UserDetails wangwu = User.withUsername("wangwu")
  63. .password(passwordEncoder.encode("123456"))
  64. .roles("admin")
  65. .authorities("file_write","world_exec")
  66. .build();
  67. //默认内存中保存所有用户信息
  68. InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(zhangsan, lisi, wangwu);
  69. return manager;
  70. }
  71. /**
  72. * 密码加密器
  73. * @return 密码加密器
  74. */
  75. @Bean
  76. PasswordEncoder passwordEncoder() {
  77. return new BCryptPasswordEncoder();
  78. }
  79. }

5.测试

无权限

  1. Welcome To Spring Security!
  2. hello
  3. world
  1. User Name :zhangsan
  2. Password:123456

提示无权限

  1. Whitelabel Error Page
  2. This application has no explicit mapping for /error, so you are seeing this as a fallback.
  3. Mon Jan 08 11:57:28 CST 2024
  4. There was an unexpected error (type=Forbidden, status=403).

有权限

  1. Welcome To Spring Security!
  2. hello
  3. world
  1. User Name :wangwu
  2. Password:123456

有权限

  1. Hello Spring Security!