Spring Boot | Spring Security ( SpringBoot安全管理 )、Spring Security中 的 “自定义用户认证“

目录 :

  • Spring Boot 安全管理 :
    • 一、Spring Security 介绍
    • 二、Spring Security 快速入门
      • 2.1 基础环境搭建 :
        • ① 创建Spring Boot 项目
        • ② 创建 html资源文件
        • ③ 编写Web控制层
      • 2.2 开启安全管理效果测试 :
        • ④ 添加 spring-boot-starter-security 启动器
        • ⑤ 项目启动测试
    • 三、"MVC Security" 安全配置介绍
    • 四、自定义 "用户认证" ( 确认用户"是否登录" , 并对登录进行 "管控" )
      • 4.1 "内存" 身份认证 ( In-Memory Authentication ) - ( 开发测试环境中使用,无法用于"实际生产环境" ) :
        • ① 自定义 WebSecurityConfigurerAdapter 配置类 ( 创建一个配置类,该类继承 WebSecurityConfigurerAdapter类 )
        • ② 使用 "内存" 进行 "身份认证"
        • ③ 效果测试
      • 4.2 "JDBC" 身份认证 ( JDBC Authentication ) - ( 将"用户登录信息" 与 "数据库信息" 进行 比对,判断是否是"合法用户" ) :
        • ① 数据准备
        • ② 添加 "JDBC 连接数据库" 的 "依赖启动器"
        • ③ application.properties 中 进行 "数据库连接配置"
        • ④ 使用 JDBC 进行 "身份认证"
        • ⑤ 效果测试
      • 4.3 "UserDetailsService" 身份认证 :
        • ① 基础项目文件准备
        • ② 定义查询用户及角色信息的服务接口
        • ③ 定义 "UserDetailsService" 用于封装认证用户信息 ( 创建类实现 "UserDetailsService接口" , 在该类中封装 "认证用户的信息" )
        • ④ 使用 UserDetailsService 进行身份认证 ( 创建一个配置类,该类继承 WebSecurityConfigurerAdapter类 , 类中重写的方法中调用 userDetailsService( )实现 "UserDetailsService身份认证" )
        • ⑤ 效果测试

Spring Boot 安全管理 :

在这里插入图片描述

作者简介 :一只大皮卡丘,计算机专业学生,正在努力学习、努力敲代码中! 让我们一起继续努力学习!

该文章参考学习教材为:
《Spring Boot企业级开发教程》 黑马程序员 / 编著
文章以课本知识点 + 代码为主线,结合自己看书学习过程中的理解和感悟 ,最终成就了该文章

文章用于本人学习使用 , 同时希望能帮助大家。
欢迎大家点赞👍 收藏⭐ 关注💖哦!!!

(侵权可联系我,进行删除,如果雷同,纯属巧合)


  • 实际开发中一些应用通常要考虑安全性问题。例如,对于一些重要的操作有些请求需要用户验明身份可以执行,还有一些请求需要用户 具有特定权限可以执行。这样做的意义不仅可以用来保护项目安全,还可以控制项目访问效果

一、Spring Security 介绍

  • 针对 项目的安全管理Spring家族提供了安全框架 : Spring Security,它是一个 基于 Spring生态圈的,用于提供安全访问控制解决方案的框架,为了方便 Spring Boot 项目安全管理Spring BootSpring Security 安全框架进行了 整合支持,并提供了 通用自动化配置,从而实现了 Spring Security 安全框架中包含的多数安全管理功能,下面,针对 常见的安全管理功能进行介绍,具体如下

    (1) MVC SecuritySpring Boot 整合 Spring MVC 搭建 Web 应用安全管理框架,也是 开发中 "使用最多一款安全功能

    (2) WebFlux SecuritySpring Boot 整合 Spring WebFlux 搭建 Web 应用安全管理。虽然 Spring WebFlux 框架刚出现不久、文档不够健全,但是它集成了其他安全功能的优点,后续有可能在 Web 开发中越来越流行。

    (3) OAuth2大型项目安全管理框架,可以实现 第三方认证单点登录 等功能,但是目前 Spring Boot 版本
    还不支持 OAuth2 安全管理框架。

    (4) Actuator Security用于对项目的一些 运行环境提供安全监控,例如 Health 健康信息、Info 运行信息等,它主要作为系统指标供运维人员查看管理系统的运行情况。


    上面介绍Spring Boot 整合 Spring Security 安全框架可以实现的一些安全管理功能项目安全管理是一个很大的话题,开发者可以 根据实际项目需求选择性地 使用 Spring Security 安全框架 中的功能

二、Spring Security 快速入门

  • Spring Security安全管理两个重要概念,分别是 Authentication ( 认证 )和 Authorization ( 授权 )。其中,
    认证确认用户是否登录,并对 用户登录 进行 管控
    授权确定用户所拥有功能权限,并对 用户权限进行管控
  • 本章后续将对 Spring Boot 整合 Spring Security 进行安全管理的讲解和实现将围绕用户登录管理访问权限控制进行。下面我们先通过一个 快速入门案例 来体验 Spring Boot 整合 Spring Security 实现的 MVC Security 安全管理效果

2.1 基础环境搭建 :

  • 为了更好地使用 Spring Boot 整合实现 MVC Security 安全管理功能,实现 Authentication( 认证 )Authorization
    ( 授权 ) 的功能,下面通过一个案例进行演示讲解
① 创建Spring Boot 项目
  • 创建项目 :
    在这里插入图片描述


    项目结构

    在这里插入图片描述

② 创建 html资源文件
  • 创建 html资源文件 :
    index.html页面是项目首页页面commonvip文件夹中分别对应普通用户VIP用户可访问的页面

    index.html :

    <!DOCTYPE html>
    <!-- 配置开启thymeleaf模板引擎页面配置 -->
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>影视直播厅</title>
    </head>
    <body>
    
    <!-- index.html页面是项目首页页面,common和vip文件夹中分别对应的普通用户 和 VIP用户可访问的页面 -->
    <h1 align="center">欢迎进入电影网站首页</h1>
    <hr>
    <h3>普通电影</h3>
    <ul>
        <li><a th:href="@{/detail/common/1}">飞驰人生</a></li>
        <li><a th:href="@{/detail/common/2}">夏洛特烦恼</a></li>
    </ul>
    <h3>VIP专享</h3>
    <ul>
        <li><a th:href="@{/detail/vip/1}">速度与激情</a></li>
        <li><a th:href="@{/detail/vip/1}">猩球崛起</a></li>
    </ul>
    </body>
    </html>
    

    1.html : ( 其他三个页面以此类推 )

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <!-- th:href="@{/}" : 返回项目首页-->
    <a th:href="@{/}">返回</a>
    <h1>飞驰人生</h1>
    .....
    </body>
    </html>
    
③ 编写Web控制层
  • FileController.java :

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    
    @Controller //加入到IOC容器
    public class FileController { //控制层类
        //影片详情页
        @GetMapping("/detail/{type}/{path}") //为路径变量
        public String toDetail(@PathVariable("type") String type, @PathVariable("path") String path) {
            //返回值为String类型,可用于返回视图页面
            return "detail/" + type + "/" + path;
        }
    
    }
    

2.2 开启安全管理效果测试 :

④ 添加 spring-boot-starter-security 启动器
  • Spring Boot 项目开启 Spring Security方式非常简单,只需要引入 spring-boot-starter-security 启动器即可。

    <!-- Spring Security 的依赖启动器,其版本号由SpringBoot进行统一管理-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    

    需要说明的是,一旦项目 引入 spring-boot-starter-security 启动器MVC SecurityWebFlux Security 负责的 安全功能都会立即生效

    ps :
    WebFlux Security 生效另一个前提是项目 属于 WebFlux Web 项目 );
    ② 对于 OAuth2 安全管理功能来说,则还
    需要额外引入
    一些其他安全依赖

⑤ 项目启动测试
  • 启动项目后,仔细 查看控制台打印信息项目启动时会在 "控制台"上 自动生成一个“安全密码” ( security password ) , 这个
    密码每次项目启动时 "随机生成" 的 ,如下图所示 :

    在这里插入图片描述

  • 此时通过浏览器访问 http://localhost:8080/ 访问 项目首页,会自动跳转到一个新的登录链接页面 : http://localhost:8080/login , 这说明在项目添加 spring-boot-starter-security依赖启动器后,项目实现Spring Security自动化配置,并且 具有了一些默认安全管理功能。另外,项目中并没有手动创建用户登录页面,而添加了Security 依赖后Spring Security自带一个默认登录页面如下图所示 :

    在这里插入图片描述

  • 登录页面随意输入一个错误用户名密码,会出现 错误提示,效果如下图所示 :

    在这里插入图片描述

    上图可以看出,当在 Spring Security 提供的默认登录页面“/ogin”中输入错误登录信息后,会 重定向到“/ogin?error页面并显示出错误信息“用户名或密码错误”。

    需要说明的是,在 Spring Boot 项目中加入 spring-boot-starter-security 依赖启动器Security 会默认提供一个可登录的用户信息,其中 用户名user密码随机生成,这个密码随着项目每次启动随机生成打印在控制台 上。

  • 输入账号密码 后,会 自动跳转 到 “登录首页” :

    在这里插入图片描述

    注意点 :

    这种默认安全管理方式存在诸多问题例如,只有唯一的默认登录用户 :user密码随机生成过于暴露登录页面错误提示页面不是我们想要的等

三、“MVC Security” 安全配置介绍

  • 使用 Spring BootSpring MVC 进行 Web 开发时,如果项目引入 spring-boot-starter-security 依赖启动器MVC Security 安全管理功能就会自动生效,其 默认安全配置 是在 SecurityAutoConfiguration
    UserDetailsServiceAutoConfiguration实现的

  • 其中, SecurityAutoConfiguration导入并自动化配置 : SpringBootWebSecurityConfiguration用于启动 Web安全管理 UserDetailsServiceAutoConfiguration 则用于 配置用户身份信息

  • 通过自定义 WebSecurityConfigurerAdapter 类型的 Bean 组件,可以 完全关闭 Security 提供的 Web 应用默认安全配置,但是 不会关闭 UserDetailsService 用户信息自动配置类如果要关闭 UserDetailsService默认用户信息配置,可以自定义UserDetailsServiceAuthenticationProviderAuthenticationManager 类型的 Bean 组件

    另外,可以通过自定义 WebSecurityConfigurerAdapter 类型的 Bean 组件 覆盖默认访问规则。Spring Boot 提供了非常多方便的方法,可用于覆盖请求映射静态资源的访问规则

  • 下面我们通过 Spring Security API查看 WebSecurityConfigurerAdapter主要方法,具体如下表所示

    方法描述
    configure ( AuthenticationManagerBuilder auth )定制用户认证管理器来实现 用户认证 ( 确认用户"是否登录" ,并对登录进行 “管控” )
    configure ( HttpSecurity http )定制基于 HTTP 请求用户访问控制 ( 权限管理 / 授权管理 )

四、自定义 “用户认证” ( 确认用户"是否登录" , 并对登录进行 “管控” )

  • 通过 自定义 WebSecurityConfigurerAdapter 类型Bean 组件重写 confiqure ( AuthenticatiorManagerBuilder auth ) 方法,可以 自定义用户认证

  • 针对 自定义用户认证Spring Security 提供了 多种自定义认证方式,包括有:

    In-Memory Authentication ( 内存身份认证 )
    JDBCAuthentication( JDBC 身份认证 )

    LDAP Authentication( LDAP 身份认证 )
    AuthenticationProvider(身份认证提供商)
    UserDetailsService( 身份详情服务 )


    下面我们选取其中 3个比较有代表性方式讲解如何 实现自定义用户认证

4.1 “内存” 身份认证 ( In-Memory Authentication ) - ( 开发测试环境中使用,无法用于"实际生产环境" ) :

  • In-Memory Authentication ( 内存身份认证 ) 是 最简单身份认证方式 ( 用户凭证 :如 用户名密码角色存储在内存中,当用户尝试登录时,应用程序会在 内存查询和匹配是否有该用户 ) ,主要 用于Security安全认证体验测试
  • 自定义内存身份认证时,只需要在 重写configure ( AuthenticationManagerBuilder auth ) 方法中定义测试用户即可
  • 下面通过 Spring Boot 整合 Spring Security 实现 内存身份认证具体步骤如下
① 自定义 WebSecurityConfigurerAdapter 配置类 ( 创建一个配置类,该类继承 WebSecurityConfigurerAdapter类 )
  • 上面已经创建的项目基础上,创建 配置类 : SecurityConfig,该继承 WebSecurityConfigurerAdapter

    SecurityConfig.java

    import org.springframework.security.config.annotation.web.configuration.*;
    
    @EnableWebSecurity //开启MVC Security 安全支持
    public class SecurityConfig extends WebSecurityConfigurerAdapter{ //关于Spring Boot 安全管理 (安全框架) 的 配置类
    
    }
    

    上述代码中自定义了一个 继承WebSecurityConfigurerAdapterSecurityConfig 配置类,用于进行 MVC Security 自定义配置,该类上方的 @EnableWebSecurity 注解是一个组合注解其效果等同于 :
    @Configuration@lmport@EnableGlobalAuthentication组合用法,关于这些注解介绍具体如下:

    注解描述
    @Configuration 注解标记该类SpringBoot 的 " 配置类"。
    @lmport 注解根据pom.xml导入Web模块Security模块 进行 自动化配置
    @EnableGlobalAuthentication 注解用于 开启自定义全局认证
② 使用 “内存” 进行 “身份认证”
  • 自定义SecurityConfig 类重写 configure( AuthenticationManagerBuilder auth )方法 , 并在该方法使用内存身份认证方式进行 自定义用户认证 :

    SecurityConfig.java

    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.configuration.*;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    
    @EnableWebSecurity //开启MVC Security 安全支持
    public class SecurityConfig extends WebSecurityConfigurerAdapter{ //关于 "内存身份认证" 的 配置类
    
        /**
         * 重写configure()方法,并在该方法中使用"内存身份认证"的方式进行"自定义用户认证"
         */
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
            //密码需要设置编码器 (创建一个"密码编辑器")
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    
            /*
               ① auth.inMemoryAuthentication() : 将创建一组"硬编码"的 "用户名和密码",它们将用于身份验证 ,
               这种方式在"开发和测试环境"中非常有用,但在生产环境中可能不是最佳选择,因为用户名和密码直接存储在代码中。
    
               ② 在Spring Security中配置了 "内存" 中的"用户身份验证" , 配置了两个用户 ,这两个用户可以直接用于身份验证,无需连接"数据库"或"其他外部数据源"。
             */
            auth.inMemoryAuthentication()
                     //设置一个"密码编辑器",用于在存储密码之前对其进行编码,这很重要,因为不能以明文形式存储密码。密码编码器可以将密码转换为一个不可逆的散列值
                    .passwordEncoder(encoder)
                     //为用户名"张三"创建一个用户,密码为"123456"(已编码),该用户具有"common角色"
                    .withUser("张三").password(encoder.encode("123456")).roles("common")
                    //这是链式编程的一个常见模式,用于分隔不同的配置部分。
                    .and()
                    //为用户名"李四"创建一个用户,密码为"123456"(已编码),该用户具有"common角色"
                    .withUser("李四").password(encoder.encode("123456")).roles("vip");
                          //配置了内存中的用户身份验证,设置了两个账户,两个用户可以直接用于身份验证,而无需连接数据库或其他外部数据源。
          }
     }
    

    上面的代码文件中,重写WebSecurityConfigurerAdapter 类configure ( AuthenticationManageBuilder auth ) 方法,并在该方法中使用内存身份认证的方式自定义了认证用户信息定义用户认证信息时,设置了两个用户,包括用户名密码角色
    ( 存储用户凭证 / 登录信息内存中,当用户进行登录时,将登录信息内存信息进行比对,进行“身份认证” )


    注意点 :

    上面的代码文件中进行的 自定义用户认证时,需要注意以下几个问题
    (1) 从 Spring Security 5开始自定义用户认证必须
    设置密码编码器用于保护密码
    ,否则控制台会出现 “llegalArgumentException: There is no PasswordEncoder mapped for the idn"nul"”异常错误

    (2) Spring Security 提供了多种密码编码器,包括 BcryptPasswordEncoderPbkdf2PasswordEncoderScryptPasswordEncoder等,密码设置不限于本例中的 BcryptPasswordEncoder 密码编码器。

    (3) 自定义用户认证时可以定义用户角色roles也可以定义用户权限 authorities。在进行赋值时,权限通常是在角色值基础上添加“ROLE”前级。例如,authorities("ROLE_common”)roles(“common”)等效的

    (4) 自定义用户认证时,可以为 某个用户 “一次指定多个” 角色权限,例如 roles ( “common”,“vip” ) 或者 authorities(“ROLE common”," ROLE_vip")

③ 效果测试
  • 此时重新启动项目启动成功后,可以看到==**控制台没有默认发现没有默认安全管理时随机生成 **的 密码==了,如下图所示 :

    在这里插入图片描述


    此时通过浏览器访问 http://localhost:8080/ 访问 项目首页效果如下图所示

    在这里插入图片描述

    从上图可以看出 执行 http://localhost:8080/ 访问首页同样自动跳转到了用户登录页面“http://localhost:8080/login”。
    如果输入的用户名或者密码错误,会出现相应错误提示效果如下图1所示。如果输入的用户名密码正确,那么会跳转进入网站首页效果如下图2所示

    在这里插入图片描述

    在这里插入图片描述

    此时点击电影名称同样可以查看电影详情,说明通过内存身份认证方式实现了自定义用户认证

    实际开发中用户都是在 页面注册登录 时进行认证管理的,而 非在程序内部 使用 内存管理的方式手动控制注册用户,所以上述使用内存身份认证的方式 无法用于实际生产,只可以作为初学者测试使用,或者可在测试开发环境使用。 )

4.2 “JDBC” 身份认证 ( JDBC Authentication ) - ( 将"用户登录信息" 与 “数据库信息” 进行 比对,判断是否是"合法用户" ) :

  • JDBC 身份认证 : JDBC Authentication , 是通过 JDBC 连接数据库已有用户身份进行认证,下面通过一个案例讲解 JDBC 身份认证
① 数据准备
  • JDBC 身份认证本质是使用 数据库中已有的用户信息在项目中实现用户认证服务,所以需要提前准备好相关数据。这里我们使用之前创建springbootdata数据库,在该数据库中创建3个表t_customert_authorityt_customer_authority,并预先插入几条测试数据。

    security.sql


    注意点 :

    使用 JDBC 身份认证方式创建用户/权限表以及初始化数据时,应特别注意以下几点 :

    (1) 创建用户表t_customer 时,用户名 username 必须唯一,因为 Security 在进行用户查询时是 先通过 username 定位是否存在唯一用户 的。

    (2) 创建用户表t_customer 时,必须额外定义一个 tinyint类型字段 (对应 boolean 类型属性,例如示例中的 valid ),用于 校验用户身份是否合法 (默认都是合法的)

    (3) 初始化用户表 t_customer 数据时,插入的用户密码 password 必须是对应 编码器编码后的密码,例如示例中的 密码:y2ay10y5ooQl8dir8jv0/gCa1Six.GpzAdIPf6pMgdminZ/3ijYzivCyPIfK 是使用 BcryptPasswordEncoder 密码加密后的形式 ( 对应的原始密码123456)。因此
    自定义配置类 中进行 用户密码查询 时,必须 使用与数据库密码统一密码编码器进行 编码

    (4)初始化权限表 t_authority 数据时,权限 authority必须 带有“ROLE ”前缀,而 默认用户角色值 则是 对应权限值去掉“ROLE”前缀

② 添加 “JDBC 连接数据库” 的 “依赖启动器”
  • pom.xml文件中,添加 Mysql数据库连接驱动的依赖JDBC连接依赖 :

    <!-- JDBC数据库连接启动器-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    
    <!-- Mysql数据连接驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    
③ application.properties 中 进行 “数据库连接配置”
#Mysql数据库连接配置 (配置数据库信息)
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT&nullCatalogMeansCurrent=true
spring.datasource.username=root
spring.datasource.password=root
④ 使用 JDBC 进行 “身份认证”
  • 完成准备工作后,在 configure ( AuthenticationManagerBuilder auth )方法 中使用 JDBC 身份认证的方式进行自定义用户认证代码例子如下

    SecurityConfig.java

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    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 javax.sql.DataSource;
    
    //使用 JDBC 进行身份认证
    @EnableWebSecurity //开启MVC Security 安全支持
    public class SecurityConfig extends WebSecurityConfigurerAdapter{ //关于 "JDBC身份认证" 的 配置类
    
        @Autowired
        private DataSource dataSource;
    
        /**
         * 重写configure()方法,并在该方法中使用"JDBC身份认证"的方式进行"自定义用户认证"
         */
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //密码需要设置编码器 (创建一个"密码编辑器")
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    
            /**
              使用 JDBC 进行身份认证
             */
    
            String userSQL ="select username,password,valid from t_customer " +
                    "where username = ?";
            String authoritySQL="select c.username,a.authority from t_customer c,t_authority a,"+
                    "t_customer_authority ca where ca.customer_id=c.id " +
                    "and ca.authority_id=a.id and c.username =?";
    
            //使用 JDBC 进行身份认证
            auth.jdbcAuthentication()
                    //设置密码编码器
                    .passwordEncoder(encoder)
                    // 设置数据源
                    .dataSource(dataSource)
                    //设置一个自定义的SQL查询,用于根据"用户名"查找"用户信息"
                    .usersByUsernameQuery(userSQL)
                    //设置一个自定义的SQL查询,用于根据"用户名"查找"用户的权限信息"
                    .authoritiesByUsernameQuery(authoritySQL);
        }
    }
    

    上面的代码中,先使用 @Autwired 注解装配了 DataSource 数据源重写的方法 : configure( AuthenticationManagerBuilderaut ) 方法中使用 JDBC 身份认证的方式进行身份认证

    使用 JDBC 身份认证 时,首先需要对 密码 进行 编码设置 ( 必须与数据库中用户密码加密方式一样 ) , 然后需要加载 JDBC 进行认证连接数据源 DataSource ; 最后,执行SQL语句,实现 通过用户名 username 查询用户信息用户权限

⑤ 效果测试

和之前的访问url测试流程一样的

4.3 “UserDetailsService” 身份认证 :

  • 对于 用户流量较大项目来说,频繁地使用JDBC 进行 数据库查询认证不仅麻烦,而且 会降低网站响应速度对于一个 完善的项目来说,如果某些业务 已经 实现了用户信息查询服务 ,就 没必要使用 JDBC 进行身份认证 了。
  • "UserDetailsService" 身份认证 代码 案例如下
① 基础项目文件准备

创建项目 : ( 查询mysql数据库用的mybatis框架 )

在这里插入图片描述


项目结构

在这里插入图片描述


pom.xml :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>2.1.3.RELEASE</version>
       <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.myh</groupId>
    <artifactId>chapter_21</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>chapter_21</name>
    <description>chapter_21</description>
    <properties>
       <java.version>1.8</java.version>
    </properties>
    <dependencies>

       <!--  该依赖中的version不能省略,因为其是阿里巴巴为了迎合Springboot而有,不是Springboot自己制作的  -->
       <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid-spring-boot-starter</artifactId>
       </dependency>

       <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-redis</artifactId>
       </dependency>

       <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-jdbc</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-thymeleaf</artifactId>
       </dependency>

       <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
       </dependency>

<!--       <dependency>-->
<!--          <groupId>org.thymeleaf.extras</groupId>-->
<!--          <artifactId>thymeleaf-extras-springsecurity6</artifactId>-->
<!--       </dependency>-->

       <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <scope>runtime</scope>
       </dependency>

       <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-test</artifactId>
          <scope>test</scope>
       </dependency>

       <dependency>
          <groupId>org.springframework.security</groupId>
          <artifactId>spring-security-test</artifactId>
          <scope>test</scope>
       </dependency>

       <dependency>
          <groupId>org.mybatis.spring.boot</groupId>
          <artifactId>mybatis-spring-boot-starter</artifactId>
          <version>2.0.1</version>
       </dependency>

       <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid-spring-boot-starter</artifactId>
          <version>1.1.10</version>
       </dependency>

<!--       <dependency>-->
<!--          <groupId>org.junit.jupiter</groupId>-->
<!--          <artifactId>junit-jupiter</artifactId>-->
<!--          <version>RELEASE</version>-->
<!--          <scope>test</scope>-->
<!--       </dependency>-->

    </dependencies>

<!--    <build>-->
<!--       <plugins>-->
<!--          <plugin>-->
<!--             <groupId>org.springframework.boot</groupId>-->
<!--             <artifactId>spring-boot-maven-plugin</artifactId>-->
<!--          </plugin>-->
<!--       </plugins>-->
<!--    </build>-->

</project>

导入 Sql文件 ( 创建数据库表 ) :
security.sql


Customer.java

import java.io.Serializable;


public class Customer implements Serializable { //数据库表对应的实体类

 private Integer id;

 //表示数据库表中“字段名”对应的属性 (如果“字段名”和“属性名”一致,则可不用配置该注解)
 private String username;

 private String password;

 private Integer valid;

 public Integer getId() {
     return id;
 }

 public void setId(Integer id) {
     this.id = id;
 }

 public String getUsername() {
     return username;
 }

 public void setUsername(String username) {
     this.username = username;
 }

 public String getPassword() {
     return password;
 }

 public void setPassword(String password) {
     this.password = password;
 }

 public Integer getValid() {
     return valid;
 }

 public void setValid(Integer valid) {
     this.valid = valid;
 }

 @Override
 public String toString() {
     return "Customer{" +
             "id=" + id +
             ", username='" + username + '\'' +
             ", password='" + password + '\'' +
             ", valid=" + valid +
             '}';
 }
}

Authority.java

import java.io.Serializable;

public class Authority implements Serializable {

 private Integer id;
 private String authority;

 public Integer getId() {
     return id;
 }

 public void setId(Integer id) {
     this.id = id;
 }

 public String getAuthority() {
     return authority;
 }

 public void setAuthority(String authority) {
     this.authority = authority;
 }

 @Override
 public String toString() {
     return "Authority{" +
             "id=" + id +
             ", authority='" + authority + '\'' +
             '}';
 }
}

CustomerMapper.java

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface CustomerMapper {

 /**
     *  根据username查询信息
     */
    @Select("select username,password,valid from t_customer where username =#{username}")
    Customer findByUsername(String username);
}

AuthorityMapper.java

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;


@Mapper
public interface AuthorityMapper {

    String authoritySQL = "select a.authority from t_customer c, t_authority a, t_customer_authority ca " +
            "where ca.customer_id = c.id " +
            "and ca.authority_id = a.id " +
            "and c.username = #{username}";

    /**
     *  根据username查询"权限信息"
     */
    @Select(authoritySQL)
    List<Authority> findAuthoritiesByUsername(String username);

}

主程序启动类 :

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.myh.chapter_21.mapper") //将该包下的所有接口都加入到IOC容器中
public class Chapter21Application {

    public static void main(String[] args) {
       SpringApplication.run(Chapter21Application.class, args);
    }
}

application.properties

#allowPublicKeyRetrieval=true
#配置Mysql数据库信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT&nullCatalogMeansCurrent=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

#添加并配置第三方数据源Druid(数据库连接池)
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#初始化时创建的连接数。当应用程序启动时,连接池会立即创建这么多连接。
spring.datasource.initialSize=20
#连接池中最小的空闲连接数。连接池会维护至少这么多的空闲连接,当空闲连接数低于这个数值时,连接池会创建新的连接。
spring.datasource.minIdle=10
#连接池中最大的活动连接数。这表示在任何时候,连接池中的活动(即被使用的)连接数不会超过这个数值。如果所有连接都在使用中,并且达到这个上限,那么新的数据库连接请求将被阻塞或拒绝,直到有连接可用。
spring.datasource.maxActive=100


#配置Redis数据库连接信息/连接参数
spring.redis.host=127.0.0.1
#连接服务端口
spring.redis.port=6379
#连接密码 (默认为空)
spring.redis.password=123456

创建 html资源文件 :
index.html页面是项目首页页面commonvip文件夹中分别对应普通用户VIP用户可访问的页面

index.html :

<!DOCTYPE html>
<!-- 配置开启thymeleaf模板引擎页面配置 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>影视直播厅</title>
</head>
<body>

<!-- index.html页面是项目首页页面,common和vip文件夹中分别对应的普通用户 和 VIP用户可访问的页面 -->
<h1 align="center">欢迎进入电影网站首页</h1>
<hr>
<h3>普通电影</h3>
<ul>
    <li><a th:href="@{/detail/common/1}">飞驰人生</a></li>
    <li><a th:href="@{/detail/common/2}">夏洛特烦恼</a></li>
</ul>
<h3>VIP专享</h3>
<ul>
    <li><a th:href="@{/detail/vip/1}">速度与激情</a></li>
    <li><a th:href="@{/detail/vip/1}">猩球崛起</a></li>
</ul>
</body>
</html>

1.html : ( 其他三个页面以此类推 )

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!-- th:href="@{/}" : 返回项目首页-->
<a th:href="@{/}">返回</a>
<h1>飞驰人生</h1>
.....
</body>
</html>
② 定义查询用户及角色信息的服务接口
  • 定义查询用户及角色信息的服务接口,在项目中创建一个 CustomerService业务处理类,用来通过用户名查询

    户信息权限信息 :

    CustomerService.java

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.cache.RedisCacheManager;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.ValueOperations;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    // 对用户
    @Service //加入到IOC容器
    public class CustomerService {
          @Autowired
      private CustomerMapper customerMapper;
    
      @Autowired
      private AuthorityMapper authorityMapper;
    
          @Autowired
      private RedisTemplate redisTemplate; //通过 Redis API 的方式来进行 "Redis缓存"
    
          /**
       * 业务控制 : 使用唯一用户名查询用户信息
       */
      public Customer getCustomer(String username) {
          Customer customer = null;
          //从Redis数据库中获取"缓存数据"
          ValueOperations valueOperations = redisTemplate.opsForValue();
          Object obj = valueOperations.get("customer_" + username);//获得指定名称的"缓存数据"
          //判断是否有该缓存数据
          if (obj != null) {
              customer = (Customer) obj;
          } else { //不存在该缓存数据,则从数据库中查询缓存数据
              customer = customerMapper.findByUsername(username); //根据username来在数据库中查询数据
              if (customer != null) {
                  redisTemplate.opsForValue().set("customer_"+username,customer);
              }
          }
          return customer;
      }
    
      /**
       * 业务控制 : 使用"唯一用户名"查询用户权限
       */
      public List<Authority> getCustomerAuthority(String username) {
          List<Authority> authorities = null;
          //尝试从Redis数据库中获得缓存数据
          Object obj = redisTemplate.opsForValue().get("authorities_" + username);
          if (obj != null) {
              authorities = (List<Authority>) obj;
          } else {
              //没找到缓存数据则从Mysql数据库中查询数据
              authorities = authorityMapper.findAuthoritiesByUsername(username);
              //如果查询到了数据
              if (authorities.size() > 0) {
                  redisTemplate.opsForValue().set("authorities"+username,authorities);
              }
          }
            return authorities;
          }
       }
    
③ 定义 “UserDetailsService” 用于封装认证用户信息 ( 创建类实现 “UserDetailsService接口” , 在该类中封装 “认证用户的信息” )
  • UserDetailsService接口Security 提供的用于 封装认证用户信息接口,该接口提供loadUserByUsername(Strings) 方法用于通过用户名加载用户信息。使用 UserDetailsService 进行 身份认证时,自定义一个UserDetailsService接口实现类,通过loadUserByUsername(String s)方法 封装用户详情信息返回 UserDetails 对象Security 认证使用

    UserDetailServiceImpl.java

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    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.core.userdetails.UsernameNotFoundException;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    //自定义一个UserDetailsService接口实现"用户认证信息"封装 : 在其中封装"用户认证信息"
    @Service
    public class UserDetailServiceImpl implements UserDetailsService { //实现 UserDetailsService接口
    
        @Autowired
        private CustomerService customerService;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            /**
              通过业务方法(业务层类)获取用户以及权限信息
             */
            //根据username获得Customer对象信息
            Customer customer = customerService.getCustomer(username);
            //根据username获得 "权限信息"
            List<Authority> authorities = customerService.getCustomerAuthority(username);
    
            /**
             * 对用户权限进行封装
             */
            List<SimpleGrantedAuthority> list = authorities
                    //"权限信息"集合 转换为一个流(Stream) , 以便进行后续的流式操作
                    .stream()
    
                    /*
                       使用map操作 / map()函数 来转换流中的每个元素 (将流中的"每一个元素"转换为 "另一种形式")
                       具体分析:
                       authority -> 获得流中的每一个元素,将其转换为另一种形式
                       authority.getAuthority() : 获得 authority 这个元素对象的"权限信息" ( 是一个"权限信息"的字符串 )
                       new SimpleGrantedAuthority(authority.getAuthority())) : 使用这个 "权限信息字符串" 创建一个 SimpleGrantedAuthority对象,
                       该对象 是 Spring Security框架中用于表示 "授权信息" 的类
                     */
                    .map(authority -> new SimpleGrantedAuthority(authority.getAuthority()))
    
                    /*
                      以下是一个终端操作,它告诉流如何收集其元素以生成一个结果。
    
                      具体分析:
                      .collect(Collectors.toList()) : 收集转换后的 SimpleGrantedAuthority对象,并将其放入一个新的列表中
                     */
                    .collect(Collectors.toList());
    
            /**
             *  创建 UserDetails (用户详情) 对象,并将该对象进行返回
             */
            if (customer != null) {
                //用 username 、password 、权限信息集合 作为参数创建 UserDetails对象 ( 用户详情对象 )
                UserDetails userDetails = new User(customer.getUsername(), customer.getPassword(), list);
                return userDetails;
            } else {
                //如果查询的用户不存在 (用户名不存在 ) , 必须抛出异常
                throw new UsernameNotFoundException("用户名不存在!");
            }
        }
    }
    

    在上面的文件代码中,重写UserDetailsService接口loadUserByUsername( )方法 ,用于借助 CustomerService 业务处理类获取 用户信息权限信息 ,并通过 UserDetails 进行认证信息封装

    需要注意的是
    CustomerService 业务处理类获取User 实体类时必须对当前用户进行 非空判断,这里使用 throw 进行异常处理,如果 查询的用户为空 ,throw会抛出 UsernameNotFoundException 的异常。如果没有 使用 throw 异常处理 ,Security 将无法识别导致程序整体报错

④ 使用 UserDetailsService 进行身份认证 ( 创建一个配置类,该类继承 WebSecurityConfigurerAdapter类 , 类中重写的方法中调用 userDetailsService( )实现 “UserDetailsService身份认证” )
  • SecurityConfig.java

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.WebSecurity;
    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;
    
    @EnableWebSecurity //开始MVC security身份认证
    public class SecurityConfig extends WebSecurityConfigurerAdapter { // 该类为 : 进行 "UserDetailsService"身份认证 的 "配置类"
    
        @Autowired
        private UserDetailServiceImpl userDetailService; //该类为 配置好了"UserDetailsService"身份认证 信息的类,使用该类来进行 "UserDetailsService"身份认证
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //密码需要设置编码器 ( 添加"密码编辑器")
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            //使用UserDetailService进行"身份认证"
            auth.userDetailsService(userDetailService)
                    //设置"密码编辑器"
                    .passwordEncoder(encoder);
        }
    }
    
⑤ 效果测试

和之前的访问url测试流程一样的


至此 ,关于 Spring Boot 整合 Spring Security 中的 自定义用户认证 知识讲述完毕内存身份认证最为简单,主要用作测试新手体验; JDBC 身份认证UserDetailsService 身份认证实际开发中使用较多,而这两种认证方式的选择,主要根据实际开发中已有业务支持来确定

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/583603.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Dockerfile部署LNMP

目录 一、项目模拟 1. 项目环境 2. 服务器环境 3. 任务需求 二、Linux系统基础镜像 三、Nginx 1. 建立工作目录 2. 编写Dockerfile脚本 3. 准备nginx.conf配置文件 4. 生成镜像 5. 创建自定义网络 6. 启动镜像容器 7. 验证nginx 四、Mysql 1. 建立工作目录 2. …

# 使用 spring boot 时,@Autowired 注解 自动装配注入时,变量报红解决方法:

使用 spring boot 时&#xff0c;Autowired 注解 自动装配注入时&#xff0c;变量报红解决方法&#xff1a; 1、使用 Resource 代替 Autowired 注解&#xff0c;根据类型注入改为根据名称注入&#xff08;建议&#xff09;。 2、在 XXXMapper 上添加 Repository 注解&#xff0…

(2024,一致性模型,强化学习,MDP,DDPO)一致性模型的强化学习:更快的奖励引导文本到图像生成

RL for Consistency Models: Faster Reward Guided Text-to-Image Generation 公和众和号&#xff1a;EDPJ&#xff08;进 Q 交流群&#xff1a;922230617 或加 VX&#xff1a;CV_EDPJ 进 V 交流群&#xff09; 部分图像上传缓慢&#xff0c;可看原论文或在 EDPJ 查看 目录 …

2024/4/29 英语每日一段

Many have turned to cheaper, hand-rolled tobacco instead of normal cigarettes, with young women telling The Times that the habit was a social way to get rid of “anxious energy”. The news comes as the government voted on Tuesday to phase out smoking in Br…

RCE复习(ctfhub下)

先了解一下命令注入的知识点&#xff1a; 知识点 1、常见的拼接符 A ; B 先执行A&#xff0c;再执行BA & B 简单的拼接A | B 显示B的执行结果A&&B A执行成功之后才会执行BA || B A执行失败之后才会执行B , 在特殊情况下可代替空格…

pytorch 实现语义分割 PSPNet

语意分割是指一张图片上包含多个物体&#xff0c;通过语义分割可以识别物体分类、物体名称、像素识别的任务。和物体检测不同&#xff0c;他不会将物体框出来&#xff0c;而是根据像素的归属把物体标注出来。PSPNet 的输入是一张图片&#xff0c;例如300500&#xff0c;那么输出…

Redis基本數據結構 ― List

Redis基本數據結構 ― List 介紹常用命令範例1. 將元素推入List中2. 取得List內容3. 彈出元素 介紹 Redis中的List結構是一個雙向鏈表。 LPUSH LPOP StackLPUSH RPOP QueueLPUSH BRPOP Queue(消息隊列) 常用命令 命令功能LPUSH將元素推入列表左端RPUSH將元素推入列表右…

特别推荐一个学习开发编程的网站

http://www.somecore.cn/ 为开发人员提供一系列好看的技术备忘单&#xff0c;方便开发过程中速查基本语法、快捷键、命令&#xff0c;节省查找时间&#xff0c;提高开发效率。 【人生苦短&#xff0c;抓住重点】

Java 面向对象—重载和重写/覆盖(面试)

重载和重写/覆盖&#xff1a; 重载&#xff08;overload&#xff09;&#xff1a; Java重载是发生在本类中的&#xff0c;允许同一个类中&#xff0c;有多个同名方法存在&#xff0c;方法名可以相同&#xff0c;方法参数的个数和类型不同&#xff0c;即要求形参列表不一致。重载…

有趣的 CSS 图标整合技术!sprites精灵图,css贴图定位

你好&#xff0c;我是云桃桃。 一个希望帮助更多朋友快速入门 WEB 前端的程序媛。 云桃桃-大专生&#xff0c;一枚程序媛&#xff0c;感谢关注。回复 “前端基础题”&#xff0c;可免费获得前端基础 100 题汇总&#xff0c;回复 “前端工具”&#xff0c;可获取 Web 开发工具合…

【C语言进阶】程序编译中的预处理操作

&#x1f4da;作者简介&#xff1a;爱编程的小马&#xff0c;正在学习C/C&#xff0c;Linux及MySQL.. &#x1f4da;以后会将数据结构收录为一个系列&#xff0c;敬请期待 ● 本期内容讲解C语言中程序预处理要做的事情 目录 1.1 预处理符号 1.2 #define 1.2.1 #define定义标识…

数据结构(01)——链表OJ

目录 移除链表元素 思路1 不创建虚拟头节点 思路2 创建虚拟头节点 反转链表 寻找链表中间节点 判断链表是否相交 回文链表 环形链表 环形链表|| 移除链表元素 . - 力扣&#xff08;LeetCode&#xff09; 要想移除链表的元素&#xff0c;那么只需要将目标节点的前一…

07_for循环返回值while循环

文章目录 1.循环返回值2.yield接收for返回值3.scala调用yield方法创建线程对象4.scala中的while循环5.scala中的流程控制 1.循环返回值 for循环返回值是Unit 原因是防止产生歧义&#xff1b; 2.yield接收for返回值 // 2.yield关键字打破循环&#xff0c;可以使for循环输出…

智慧农业设备——虫情监测系统

随着科技的不断进步和农业生产的日益现代化&#xff0c;智慧农业成为了新时代农业发展的重要方向。其中&#xff0c;虫情监测系统作为智慧农业的重要组成部分&#xff0c;正逐渐受到广大农户和农业专家的关注。 虫情监测系统是一种基于现代传感技术、图像识别技术和大数据分析技…

面试笔记——线程池

线程池的核心参数&#xff08;原理&#xff09; public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler)corePoolSize …

25计算机考研院校数据分析 | 四川大学

四川大学(Sichuan University)简称“川大”&#xff0c;由中华人民共和国教育部直属&#xff0c;中央直管副部级建制&#xff0c;是世界一流大学建设高校、985工程”、"211工程"重点建设的高水平综合性全国重点大学&#xff0c;入选”2011计划"、"珠峰计划…

PostgreSQL的学习心得和知识总结(一百四十)|深入理解PostgreSQL数据库 psql工具 \set 变量内部及HOOK机制

目录结构 注&#xff1a;提前言明 本文借鉴了以下博主、书籍或网站的内容&#xff0c;其列表如下&#xff1a; 1、参考书籍&#xff1a;《PostgreSQL数据库内核分析》 2、参考书籍&#xff1a;《数据库事务处理的艺术&#xff1a;事务管理与并发控制》 3、PostgreSQL数据库仓库…

【能力展现】魔改ZXING源码实现商业级DM码检测能力

学习《OpenCV应用开发&#xff1a;入门、进阶与工程化实践》一书 做真正的OpenCV开发者&#xff0c;从入门到入职&#xff0c;一步到位&#xff01; 什么是DM码 dataMatrix是一种二维码&#xff0c;原名datacode&#xff0c;由美国国际资料公司于1989年发明。dataMatrix二维码…

GuildFi升级为Zentry的背后 链游公会的探索与转型

​链游即区块链游戏&#xff0c;指依托区块链技术构建的游戏产品。其与传统游戏的最大区别在于区块链的去中心化特性对玩家的资产有着天然的确权行为&#xff0c;因此玩家在链游中的资产是作为玩家的个人资产存在。较于 GameFi 来说&#xff0c;链游的包含范围更大&#xff0c;…

吴恩达机器学习笔记:第 8 周-14降维(Dimensionality Reduction) 14.3-14.5

目录 第 8 周 14、 降维(Dimensionality Reduction)14.3 主成分分析问题14.4 主成分分析算法14.5 选择主成分的数量 第 8 周 14、 降维(Dimensionality Reduction) 14.3 主成分分析问题 主成分分析(PCA)是最常见的降维算法。 在 PCA 中&#xff0c;我们要做的是找到一个方向…