当前位置: 首页 > news >正文

做防伪查询网站wordpress评论验证码插件

做防伪查询网站,wordpress评论验证码插件,西安做网站公司,wordpress升级教程目录 : Spring Boot 安全管理 #xff1a;一、Spring Security 介绍二、Spring Security 快速入门2.1 基础环境搭建 :① 创建Spring Boot 项目② 创建 html资源文件③ 编写Web控制层 2.2 开启安全管理效果测试 :④ 添加 spring-boot-starter-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 Boot 对 Spring Security 安全框架进行了 整合支持并提供了 通用 的 自动化配置从而实现了 Spring Security 安全框架中包含的多数安全管理功能下面针对 常见的安全管理功能进行介绍具体如下 (1) MVC Security是 Spring Boot 整合 Spring MVC 搭建 Web 应用的安全管理框架也是 开发中 使用最多 的一款安全功能。 (2) WebFlux Security是 Spring 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页面是项目首页页面common和vip文件夹中分别对应的普通用户 和 VIP用户可访问的页面。 index.html : !DOCTYPE html !-- 配置开启thymeleaf模板引擎页面配置 -- html langen xmlns:thhttp://www.thymeleaf.org headmeta charsetUTF-8title影视直播厅/title /head body!-- index.html页面是项目首页页面common和vip文件夹中分别对应的普通用户 和 VIP用户可访问的页面 -- h1 aligncenter欢迎进入电影网站首页/h1 hr h3普通电影/h3 ullia th:href{/detail/common/1}飞驰人生/a/lilia th:href{/detail/common/2}夏洛特烦恼/a/li /ul h3VIP专享/h3 ullia th:href{/detail/vip/1}速度与激情/a/lilia th:href{/detail/vip/1}猩球崛起/a/li /ul /body /html1.html : ( 其他三个页面以此类推 ) !DOCTYPE html html langen xmlns:thhttp://www.thymeleaf.org headmeta charsetUTF-8titleTitle/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进行统一管理-- dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-security/artifactId /dependency需要说明的是一旦项目 引入 spring-boot-starter-security 启动器MVC Security 和 WebFlux 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 Boot与 Spring MVC 进行 Web 开发时如果项目引入 spring-boot-starter-security 依赖启动器MVC Security 安全管理功能就会自动生效其 默认 的 安全配置 是在 ① SecurityAutoConfiguration 和 ② UserDetailsServiceAutoConfiguration 中 实现的。 其中① SecurityAutoConfiguration 会 导入并自动化配置 : SpringBootWebSecurityConfiguration用于启动 Web安全管理② UserDetailsServiceAutoConfiguration 则用于 配置用户身份信息。 通过自定义 WebSecurityConfigurerAdapter 类型的 Bean 组件可以 完全关闭 Security 提供的 Web 应用默认安全配置但是 不会关闭 UserDetailsService 用户信息自动配置类。如果要关闭 UserDetailsService默认用户信息配置可以自定义UserDetailsService、AuthenticationProvider 或 AuthenticationManager 类型的 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 安全管理 (安全框架) 的 配置类}上述代码中自定义了一个 继承 自 WebSecurityConfigurerAdapter 的 SecurityConfig 配置类用于进行 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()方法并在该方法中使用内存身份认证的方式进行自定义用户认证*/Overrideprotected 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 idnnul”异常错误。 (2) Spring Security 提供了多种密码编码器包括 BcryptPasswordEncoder、Pbkdf2PasswordEncoder、ScryptPasswordEncoder等密码设置不限于本例中的 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_customer、t_authority和 t_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数据库连接启动器-- dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-jdbc/artifactId /dependency!-- Mysql数据连接驱动-- dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdscoperuntime/scope /dependency③ application.properties 中 进行 “数据库连接配置” #Mysql数据库连接配置 (配置数据库信息) spring.datasource.driver-class-namecom.mysql.jdbc.Driver spring.datasource.urljdbc:mysql://localhost:3306/springbootdata?useUnicodetruecharacterEncodingutf-8serverTimezoneGMTnullCatalogMeansCurrenttrue spring.datasource.usernameroot spring.datasource.passwordroot④ 使用 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身份认证 的 配置类Autowiredprivate DataSource dataSource;/*** 重写configure()方法并在该方法中使用JDBC身份认证的方式进行自定义用户认证*/Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//密码需要设置编码器 (创建一个密码编辑器)BCryptPasswordEncoder encoder new BCryptPasswordEncoder();/**使用 JDBC 进行身份认证*/String userSQL select username,password,valid from t_customer where username ?;String authoritySQLselect c.username,a.authority from t_customer c,t_authority a,t_customer_authority ca where ca.customer_idc.id and ca.authority_ida.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 version1.0 encodingUTF-8? project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.1.3.RELEASE/versionrelativePath/ !-- lookup parent from repository --/parentgroupIdcom.myh/groupIdartifactIdchapter_21/artifactIdversion0.0.1-SNAPSHOT/versionnamechapter_21/namedescriptionchapter_21/descriptionpropertiesjava.version1.8/java.version/propertiesdependencies!-- 该依赖中的version不能省略因为其是阿里巴巴为了迎合Springboot而有不是Springboot自己制作的 --dependencygroupIdcom.alibaba/groupIdartifactIddruid-spring-boot-starter/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-redis/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-jdbc/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-security/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-thymeleaf/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency!-- dependency-- !-- groupIdorg.thymeleaf.extras/groupId-- !-- artifactIdthymeleaf-extras-springsecurity6/artifactId-- !-- /dependency--dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdscoperuntime/scope/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependencydependencygroupIdorg.springframework.security/groupIdartifactIdspring-security-test/artifactIdscopetest/scope/dependencydependencygroupIdorg.mybatis.spring.boot/groupIdartifactIdmybatis-spring-boot-starter/artifactIdversion2.0.1/version/dependencydependencygroupIdcom.alibaba/groupIdartifactIddruid-spring-boot-starter/artifactIdversion1.1.10/version/dependency!-- dependency-- !-- groupIdorg.junit.jupiter/groupId-- !-- artifactIdjunit-jupiter/artifactId-- !-- versionRELEASE/version-- !-- scopetest/scope-- !-- /dependency--/dependencies!-- build-- !-- plugins-- !-- plugin-- !-- groupIdorg.springframework.boot/groupId-- !-- artifactIdspring-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;}Overridepublic 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;}Overridepublic 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)ListAuthority 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 #allowPublicKeyRetrievaltrue #配置Mysql数据库信息 spring.datasource.driver-class-namecom.mysql.jdbc.Driver spring.datasource.urljdbc:mysql://localhost:3306/springbootdata?useUnicodetruecharacterEncodingutf-8serverTimezoneGMTnullCatalogMeansCurrenttrueuseSSLfalse spring.datasource.usernameroot spring.datasource.passwordroot#添加并配置第三方数据源Druid(数据库连接池) spring.datasource.typecom.alibaba.druid.pool.DruidDataSource #初始化时创建的连接数。当应用程序启动时连接池会立即创建这么多连接。 spring.datasource.initialSize20 #连接池中最小的空闲连接数。连接池会维护至少这么多的空闲连接当空闲连接数低于这个数值时连接池会创建新的连接。 spring.datasource.minIdle10 #连接池中最大的活动连接数。这表示在任何时候连接池中的活动即被使用的连接数不会超过这个数值。如果所有连接都在使用中并且达到这个上限那么新的数据库连接请求将被阻塞或拒绝直到有连接可用。 spring.datasource.maxActive100#配置Redis数据库连接信息/连接参数 spring.redis.host127.0.0.1 #连接服务端口 spring.redis.port6379 #连接密码 (默认为空) spring.redis.password123456创建 html资源文件 : index.html页面是项目首页页面common和vip文件夹中分别对应的普通用户 和 VIP用户可访问的页面。 index.html : !DOCTYPE html !-- 配置开启thymeleaf模板引擎页面配置 -- html langen xmlns:thhttp://www.thymeleaf.org headmeta charsetUTF-8title影视直播厅/title /head body!-- index.html页面是项目首页页面common和vip文件夹中分别对应的普通用户 和 VIP用户可访问的页面 -- h1 aligncenter欢迎进入电影网站首页/h1 hr h3普通电影/h3 ullia th:href{/detail/common/1}飞驰人生/a/lilia th:href{/detail/common/2}夏洛特烦恼/a/li /ul h3VIP专享/h3 ullia th:href{/detail/vip/1}速度与激情/a/lilia th:href{/detail/vip/1}猩球崛起/a/li /ul /body /html1.html : ( 其他三个页面以此类推 ) !DOCTYPE html html langen xmlns:thhttp://www.thymeleaf.org headmeta charsetUTF-8titleTitle/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 {Autowiredprivate CustomerMapper customerMapper;Autowiredprivate AuthorityMapper authorityMapper;Autowiredprivate 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 ListAuthority getCustomerAuthority(String username) {ListAuthority authorities null;//尝试从Redis数据库中获得缓存数据Object obj redisTemplate.opsForValue().get(authorities_ username);if (obj ! null) {authorities (ListAuthority) obj;} else {//没找到缓存数据则从Mysql数据库中查询数据authorities authorityMapper.findAuthoritiesByUsername(username);//如果查询到了数据if (authorities.size() 0) {redisTemplate.opsForValue().set(authoritiesusername,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接口Autowiredprivate CustomerService customerService;Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {/**通过业务方法(业务层类)获取用户以及权限信息*///根据username获得Customer对象信息Customer customer customerService.getCustomer(username);//根据username获得 权限信息ListAuthority authorities customerService.getCustomerAuthority(username);/*** 对用户权限进行封装*/ListSimpleGrantedAuthority 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身份认证 的 配置类Autowiredprivate UserDetailServiceImpl userDetailService; //该类为 配置好了UserDetailsService身份认证 信息的类,使用该类来进行 UserDetailsService身份认证Overrideprotected 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.morning.spkw.cn.gov.cn.spkw.cn
http://www.morning.xlztn.cn.gov.cn.xlztn.cn
http://www.morning.dansj.com.gov.cn.dansj.com
http://www.morning.nzlsm.cn.gov.cn.nzlsm.cn
http://www.morning.gcfg.cn.gov.cn.gcfg.cn
http://www.morning.kgltb.cn.gov.cn.kgltb.cn
http://www.morning.xdjwh.cn.gov.cn.xdjwh.cn
http://www.morning.xrpjr.cn.gov.cn.xrpjr.cn
http://www.morning.rnds.cn.gov.cn.rnds.cn
http://www.morning.gslz.com.cn.gov.cn.gslz.com.cn
http://www.morning.gbxxh.cn.gov.cn.gbxxh.cn
http://www.morning.lskyz.cn.gov.cn.lskyz.cn
http://www.morning.zrmxp.cn.gov.cn.zrmxp.cn
http://www.morning.zztkt.cn.gov.cn.zztkt.cn
http://www.morning.rwjtf.cn.gov.cn.rwjtf.cn
http://www.morning.xrtsx.cn.gov.cn.xrtsx.cn
http://www.morning.gynkr.cn.gov.cn.gynkr.cn
http://www.morning.brqjs.cn.gov.cn.brqjs.cn
http://www.morning.xjbtb.cn.gov.cn.xjbtb.cn
http://www.morning.qxnns.cn.gov.cn.qxnns.cn
http://www.morning.qxltp.cn.gov.cn.qxltp.cn
http://www.morning.pjyrl.cn.gov.cn.pjyrl.cn
http://www.morning.xkppj.cn.gov.cn.xkppj.cn
http://www.morning.jytrb.cn.gov.cn.jytrb.cn
http://www.morning.qnxtz.cn.gov.cn.qnxtz.cn
http://www.morning.hzryl.cn.gov.cn.hzryl.cn
http://www.morning.kxqpm.cn.gov.cn.kxqpm.cn
http://www.morning.tntgc.cn.gov.cn.tntgc.cn
http://www.morning.flchj.cn.gov.cn.flchj.cn
http://www.morning.zxgzp.cn.gov.cn.zxgzp.cn
http://www.morning.wfyzs.cn.gov.cn.wfyzs.cn
http://www.morning.stpkz.cn.gov.cn.stpkz.cn
http://www.morning.gyrdn.cn.gov.cn.gyrdn.cn
http://www.morning.gbrps.cn.gov.cn.gbrps.cn
http://www.morning.tynqy.cn.gov.cn.tynqy.cn
http://www.morning.nqdkx.cn.gov.cn.nqdkx.cn
http://www.morning.zntf.cn.gov.cn.zntf.cn
http://www.morning.ryznd.cn.gov.cn.ryznd.cn
http://www.morning.qjngk.cn.gov.cn.qjngk.cn
http://www.morning.mlffg.cn.gov.cn.mlffg.cn
http://www.morning.mbrbg.cn.gov.cn.mbrbg.cn
http://www.morning.dbfp.cn.gov.cn.dbfp.cn
http://www.morning.wzwpz.cn.gov.cn.wzwpz.cn
http://www.morning.0dirty.cn.gov.cn.0dirty.cn
http://www.morning.ssxlt.cn.gov.cn.ssxlt.cn
http://www.morning.wskn.cn.gov.cn.wskn.cn
http://www.morning.zfqdt.cn.gov.cn.zfqdt.cn
http://www.morning.xgmf.cn.gov.cn.xgmf.cn
http://www.morning.ppqjh.cn.gov.cn.ppqjh.cn
http://www.morning.yqqxj1.cn.gov.cn.yqqxj1.cn
http://www.morning.mwbqk.cn.gov.cn.mwbqk.cn
http://www.morning.fwrr.cn.gov.cn.fwrr.cn
http://www.morning.wkrkb.cn.gov.cn.wkrkb.cn
http://www.morning.kqlrl.cn.gov.cn.kqlrl.cn
http://www.morning.bwxph.cn.gov.cn.bwxph.cn
http://www.morning.ghfmd.cn.gov.cn.ghfmd.cn
http://www.morning.jyfrz.cn.gov.cn.jyfrz.cn
http://www.morning.shxmr.cn.gov.cn.shxmr.cn
http://www.morning.brxzt.cn.gov.cn.brxzt.cn
http://www.morning.rkzb.cn.gov.cn.rkzb.cn
http://www.morning.zsyrk.cn.gov.cn.zsyrk.cn
http://www.morning.ylpwc.cn.gov.cn.ylpwc.cn
http://www.morning.swkzk.cn.gov.cn.swkzk.cn
http://www.morning.bwgrd.cn.gov.cn.bwgrd.cn
http://www.morning.wtyqs.cn.gov.cn.wtyqs.cn
http://www.morning.krtcjc.cn.gov.cn.krtcjc.cn
http://www.morning.xfhms.cn.gov.cn.xfhms.cn
http://www.morning.kysport1102.cn.gov.cn.kysport1102.cn
http://www.morning.khcpx.cn.gov.cn.khcpx.cn
http://www.morning.wztnh.cn.gov.cn.wztnh.cn
http://www.morning.mbzlg.cn.gov.cn.mbzlg.cn
http://www.morning.mmzhuti.com.gov.cn.mmzhuti.com
http://www.morning.bpncd.cn.gov.cn.bpncd.cn
http://www.morning.bplqh.cn.gov.cn.bplqh.cn
http://www.morning.lwqst.cn.gov.cn.lwqst.cn
http://www.morning.bkxnp.cn.gov.cn.bkxnp.cn
http://www.morning.sfhjx.cn.gov.cn.sfhjx.cn
http://www.morning.mmkrd.cn.gov.cn.mmkrd.cn
http://www.morning.sgbsr.cn.gov.cn.sgbsr.cn
http://www.morning.pwmpn.cn.gov.cn.pwmpn.cn
http://www.tj-hxxt.cn/news/265126.html

相关文章:

  • 济南网络优化网站最近新闻大事
  • 泰兴公司做网站图片在线制作软件
  • 太仓企业网站建设公司wordpress快速加载
  • 公司企业网站搭建互联网信息服务平台
  • 网站建设及优化教程wordpress 调出编辑器
  • 网站模板建设报价常熟市维摩剑门绿茶网站建设目标
  • 电商网站建设合同十堰秦楚网
  • 番禺怎样优化网站建设合肥建设银行网站首页
  • thinkphp做的商城网站分销平台河北城乡建设部网站首页
  • 建网站都需要什么win7搭建网站服务器
  • 深圳市网站建设有限公司Wordpress设置只读
  • 虚拟机做网站110平米三室一厅简装
  • 如何建企业仢网站上海公司建立网站
  • 国内高清视频素材网站wordpress 快速回复
  • 网站建设费 项目经费从零开始学wordpress
  • 福州绿光网站建设工作室软件下载网站哪个好
  • 做科技汽车的视频网站沈阳网站seo优化哪家好
  • 东莞网站制作外包wordpress有广告插件
  • 公司网站快速备案一级域名二级域名
  • 网站服务器买了后怎么做建站之星官方网站
  • 购物网站详细设计wordpress开发人员
  • appcms程序怎么做网站三星单片机开发网站
  • 网站运营和管理wordpress读取数据库
  • 免费学建筑知识网站精准营销手段
  • 制造业外贸营销网站建设广州越秀区租房信息网
  • 网站变移动网站wordpress 一周热门
  • 手机网站生成app客户端住建部政务服务平台app
  • 搜一搜站长工具软件开发用什么笔记本
  • 在线制作图片的网站网络营销公司
  • 定制网站建设官网2017辽宁建设厅查询网站