SpringBoot3-第十篇(整合Web安全)

系列文章目录

SpringBoot3-第一篇(快速入门)

SpringBoot3-第二篇(Web开发)

SpringBoot3-第三篇(数据访问)

SpringBoot3-第四篇(基础特性)

SpringBoot3-第五篇(核心原理)

SpringBoot3-第六篇(整合NoSQL)

SpringBoot3-第七篇(整合接口文档)

SpringBoot3-第八篇(整合远程调用)

SpringBoot3-第九篇(整合消息服务)

SpringBoot3-第十篇(整合Web安全)


文章目录

  • 系列文章目录
  • [1. 安全架构](#1. 安全架构)
    • [1.1 认证:Authentication](#1.1 认证:Authentication)
    • [1.2 授权:Authorization](#1.2 授权:Authorization)
    • [1.3 攻击防护](#1.3 攻击防护)
    • [1.4 扩展 权限模型](#1.4 扩展 权限模型)
      • [1.4.1 RBAC(Role Based Access Controll)](#1.4.1 RBAC(Role Based Access Controll))
      • [1.4.2 ACL(Access Controll List)](#1.4.2 ACL(Access Controll List))
  • [2. Spring Security 原理](#2. Spring Security 原理)
    • [2.1 过滤器链架构](#2.1 过滤器链架构)
    • [2.2 FilterChainProxy](#2.2 FilterChainProxy)
    • [2.3 SecurityFilterChain](#2.3 SecurityFilterChain)
  • [3. 使用](#3. 使用)
    • [3.1 HttpSecurity](#3.1 HttpSecurity)
    • [3.2 MethodSecurity](#3.2 MethodSecurity)
  • [4. 实战](#4. 实战)
    • [4.1 引入依赖](#4.1 引入依赖)
    • [4.2 页面](#4.2 页面)
    • [4.3 配置类](#4.3 配置类)
    • [4.4 改造Hello页](#4.4 改造Hello页)

  • Apache Shiro
  • Spring Security
  • 自研:Filter

Spring Security

1. 安全架构

1.1 认证:Authentication

who are you?

登录系统,用户系统

1.2 授权:Authorization

what are you allowed to do?

权限管理,用户授权

1.3 攻击防护

  • XSS(Cross-site scripting)
  • CSRF(Cross-site request forgery)
  • CORS(Cross-Origin Resource Sharing)
  • SQL注入
  • ...

1.4 扩展 权限模型

1.4.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

1.4.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
java 复制代码
@Secured("文件 r")
public void readFile(){
    //读文件
}

2. Spring Security 原理

2.1 过滤器链架构

Spring Security利用 FilterChainProxy 封装一系列拦截器链,实现各种安全拦截功能

Servlet三大组件:Servlet、Filter、Listener

2.2 FilterChainProxy

2.3 SecurityFilterChain

3. 使用

3.1 HttpSecurity

java 复制代码
@Configuration
@Order(SecurityProperties.BASIC_AUTH_ORDER - 10)
public class ApplicationConfigurerAdapter extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/match1/**")
      .authorizeRequests()
        .antMatchers("/match1/user").hasRole("USER")
        .antMatchers("/match1/spam").hasRole("SPAM")
        .anyRequest().isAuthenticated();
  }
}

3.2 MethodSecurity

java 复制代码
@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SampleSecureApplication {
}

@Service
public class MyService {

  @Secured("ROLE_USER")
  public String secure() {
    return "Hello Security";
  }

}

核心

  • WebSecurityConfigurerAdapter
  • @EnableGlobalMethodSecurity: 开启全局方法安全配置
    • @Secured
    • @PreAuthorize
    • @PostAuthorize
  • UserDetailService: 去数据库查询用户详细信息的service(用户基本信息、用户角色、用户权限)

4. 实战

4.1 引入依赖

java 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity6</artifactId>
    <!-- Temporary explicit version to fix Thymeleaf bug -->
    <version>3.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

4.2 页面

首页

html 复制代码
<p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>

Hello页

html 复制代码
<h1>Hello</h1>

登录页

html 复制代码
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
  <head>
    <title>Spring Security Example</title>
  </head>
  <body>
    <div th:if="${param.error}">Invalid username and password.</div>
    <div th:if="${param.logout}">You have been logged out.</div>
    <form th:action="@{/login}" method="post">
      <div>
        <label> User Name : <input type="text" name="username" /> </label>
      </div>
      <div>
        <label> Password: <input type="password" name="password" /> </label>
      </div>
      <div><input type="submit" value="Sign In" /></div>
    </form>
  </body>
</html>

4.3 配置类

视图控制

java 复制代码
package com.example.securingweb;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("index");
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
    }
}

Security配置

java 复制代码
package com.atguigu.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @author lfy
 * @Description
 * @create 2023-03-08 16:54
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {


        http
                .authorizeHttpRequests((requests) -> requests
                        .requestMatchers("/", "/home").permitAll()
                        .anyRequest().authenticated()
                )
                .formLogin((form) -> form
                        .loginPage("/login")
                        .permitAll()
                )
                .logout((logout) -> logout.permitAll());

        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user =
                User.withDefaultPasswordEncoder()
                        .username("admin")
                        .password("admin")
                        .roles("USER")
                        .build();

        return new InMemoryUserDetailsManager(user);
    }
}

4.4 改造Hello页

html 复制代码
<!DOCTYPE html>
<html
  xmlns="http://www.w3.org/1999/xhtml"
  xmlns:th="https://www.thymeleaf.org"
  xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity6"
>
  <head>
    <title>Hello World!</title>
  </head>
  <body>
    <h1 th:inline="text">
      Hello <span th:remove="tag" sec:authentication="name">thymeleaf</span>!
    </h1>
    <form th:action="@{/logout}" method="post">
      <input type="submit" value="Sign Out" />
    </form>
  </body>
</html>
相关推荐
indexsunny几秒前
互联网大厂Java面试实战:从Spring Boot到微服务架构的三轮提问
java·spring boot·微服务·eureka·kafka·mybatis·spring security
2501_948120152 分钟前
云原生应用的安全开发与防护策略
安全·云原生
国科安芯28 分钟前
RISC-V架构抗辐照MCU在航天器载荷中的SEU/SEL阈值测试与防护策略
单片机·嵌入式硬件·安全·架构·安全威胁分析·risc-v
冬奇Lab42 分钟前
【Kotlin系列13】DSL设计:构建类型安全的领域语言
开发语言·安全·kotlin
戴西软件1 小时前
戴西软件发布3DViz设计与仿真数据轻量化平台
大数据·人工智能·安全·机器学习·汽车
世界尽头与你2 小时前
CVE-2024-3366_ XXL-JOB 注入漏洞
安全·网络安全·渗透测试·xxl-job
小唐同学爱学习2 小时前
缓存与数据库一致性问题
java·数据库·spring boot·缓存
没有bug.的程序员2 小时前
Spring Boot 数据访问:JPA 与 MyBatis 集成对比与性能优化深度解密
java·spring boot·性能优化·mybatis·jpa·集成对比
周某人姓周2 小时前
sql报错注入常见7个函数
sql·安全·web安全·网络安全
麦兜*2 小时前
Spring Boot 3.x 深度实战:从零构建企业级分布式微服务架构全景解析
spring boot·分布式·架构