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

spring security - 快速整合 springboot

1.引入依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version><scope>runtime</scope></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.3.1</version></dependency>2.配置 application.propertiesserver.port=8086
#
spring.application.name=security-sample
spring.main.allow-bean-definition-overriding=true
spring.mvc.static-path-pattern=/static/**
# thymeleaf 配置
spring.thymeleaf.enabled=true
spring.thymeleaf.cache=false
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html# 数据库配置
spring.datasource.name=defaultDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_plain?autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root123
# 连接池配置
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.maximum-pool-size=8
spring.datasource.hikari.minimum-idle=4
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.max-lifetime=50000
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.pool-name=HikariCP
# mybatis 配置
mybatis.mapper-locations=classpath:mappers/*xml
mybatis.type-aliases-package=com.sky.biz.entity
mybatis.configuration.map-underscore-to-camel-case=true3.定制开发 - 认证流程的 UserDetailsService说明:UserDetailsService 负责在 Security 框架中从数据源中查询出2大主要信息,
分别为:认证信息(账号、密码)、授权信息(角色列表、权限列表)。随后将这些信息封装为 UserDetails 对象返回
留作后续进行登录认证以及权限判断。@Component
public class UserDetailsServiceImpl implements UserDetailsService {@Autowiredprivate UserService userService;@Autowiredprivate RoleService roleService;@Autowiredprivate PermsService permsService;@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {BizUser bizUser = userService.queryByUserName(username);// 用户存在,查询封装用户的"角色与权限"信息到 UserDetails中,通常自定义封装对象,继承 UserDetails的子类 Userif(bizUser != null) {// 使用 authorityList 封装角色权限信息List<GrantedAuthority> authorityList = new ArrayList<>();// 查询当前用户 - 角色信息List<Role> roleList = roleService.getRoleListByUserId(bizUser.getId());for (Role role : roleList) {authorityList.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleCode()));}// 查询当前用户 - 权限信息List<Perms> permsList = permsService.getPermsListByUserId(bizUser.getId());for (Perms perm : permsList) {authorityList.add(new SimpleGrantedAuthority(perm.getPermCode()));}return new SecurityUser(bizUser, authorityList);}return null;}}4.定义封装安全信息的实体类:SecurityUserpublic class SecurityUser extends User {private BizUser bizUser;public SecurityUser(BizUser user, Collection<? extends GrantedAuthority> authorities) {super(user.getUserName(), user.getPassword(), true,true, true, true, authorities);this.bizUser = user;}public SecurityUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {super(username, password, authorities);}// get && setpublic BizUser getBizUser() {return bizUser;}public void setBizUser(BizUser bizUser) {this.bizUser = bizUser;}
}5.自定义密码校验的类:PasswordEncoder,这里自由发挥,根据各自公司安全需要自定义主要就是重写 encode(CharSequence rawPassword)  和  matches(CharSequence rawPassword, String encodedPassword) 方法
如果不想自定义就配置成spring-security提供的 BCryptPasswordEncoder 来处理密码加密与校验6.配置Security@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级别的细粒度权限控制
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserDetailsService userDetailsService;// 配置对 HTTP 请求的安全拦截处理@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/static/**").permitAll().anyRequest().authenticated().and().formLogin().and().csrf().disable().formLogin().loginPage("/login").loginProcessingUrl("/doLogin").defaultSuccessUrl("/main") .failureUrl("/fail")  .permitAll();// "/login","/main"与"/fail",都是对应 html页面访问controller跳转路径// 用户权限不够,处理并返回响应http.exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() {@Overridepublic void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {String header = request.getHeader("X-Requested-With");if("XMLHttpRequest".equals(header)) {response.getWriter().print("403"); // 返回ajax 请求对应的 json格式} else {request.getRequestDispatcher("/error403").forward(request, response);}}});}@Beanpublic MyPasswordEncoder passwordEncoder() {return new MyPasswordEncoder();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(new passwordEncoder());// 或者:auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());}
}7.使用加密时:@Autowiredprivate MyPasswordEncoder passwordEncoder;// 方法1:String encodePwd = passwordEncoder.encode(user.getPassword());// 方法2:String encodePwd = new BCryptPasswordEncoder().encode(user.getPassword());user.setPassword(encodePwd);userMapper.save(user);大体整合完成!

相关文章:

spring security - 快速整合 springboot

1.引入依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spr…...

NPM 常用命令(二)

目录 1、npm bugs 1.1 配置 browser registry 2、npm cache 2.1 概要 2.2 详情 2.3 关于缓存设计的说明 2.4 配置 cache 3、 npm ci 3.1 描述 3.2 配置 install-strategy legacy-bundling global-style omit strict-peer-deps foreground-scripts ignore-s…...

ctfhub ssrf(3关)

文章目录 内网访问伪协议读取文件扫描端口 内网访问 根据该题目&#xff0c;是让我们访问127.0.0.1/falg.php&#xff0c;访问给出的链接后用bp抓包&#xff0c;修改URL&#xff0c;发送后得到flag&#xff1a; 伪协议读取文件 这题的让我们用伪协议&#xff0c;而网站的目录…...

跨源资源共享(CORS)Access-Control-Allow-Origin

1、浏览器的同源安全策略 没错&#xff0c;就是这家伙干的&#xff0c;浏览器只允许请求当前域的资源&#xff0c;而对其他域的资源表示不信任。那怎么才算跨域呢&#xff1f; 请求协议http,https的不同域domain的不同端口port的不同 好好好&#xff0c;大概就是这么回事啦&…...

【嵌入式软件开发 】学习笔记

本文主要记录 【嵌入式软件开发】 学习笔记&#xff0c;参考相关大佬的文章 1.RTOS 内功修炼笔记 RTOS内功修炼记&#xff08;一&#xff09;—— 任务到底应该怎么写&#xff1f; RTOS内功修炼记&#xff08;二&#xff09;—— 优先级抢占式调度到底是怎么回事&#xff1f;…...

CentOS 7上安装Python 3.11.5,支持Django

CentOS 7上安装Python 3.11.5,支持Django 今天安装django&#xff0c;报了“Django - deterministicTrue requires SQLite 3.8.3 or higher upon running python manage.py runserver”。查了一番资料&#xff0c;记录下来。 参考链接&#xff1a; 参考链接: Django的web项目…...

COMPFEST 15H「组合数学+容斥」

Problem - H - Codeforces 题意&#xff1a; 定义一个集合S为T的孩子是&#xff0c;对于S中的每一个元素x&#xff0c;在T中都能找到x1。 给定n&#xff0c;k&#xff0c;每一个集合中的元素x必须满足 1 < x < k 1<x<k 1<x<k且 c n t [ x ] < 1 cnt[x…...

react快速开始(三)-create-react-app脚手架项目启动;使用VScode调试react

文章目录 react快速开始(三)-create-react-app脚手架项目启动&#xff1b;使用VScode调试react一、create-react-app脚手架项目启动1. react-scripts2. 关于better-npm-runbetter-npm-run安装 二、使用VScode调试react1. 浏览器插件React Developer Tools2. 【重点】用 VSCode …...

【C++入门】string类常用方法(万字详解)

目录 1.STL简介1.1什么是STL1.2STL的版本1.3STL的六大组件1.4STL的缺陷 2.string类的使用2.1C语言中的字符串2.2标准库中的string类2.3string类的常用接口说明 &#xff08;只讲解最常用的接口&#xff09;2.3.1string类对象的常见构造2.3.2 string类对象的容量操作2.3.3string…...

大数据错误

question1 : Could not locate Hadoop executable: D:\hadoop-3.3.1\bin\winutils.exe - 【已解决】Could not locate executable E:\Hadoop\bin\winutils.exe in the Hadoop binaries._could not locate executable e:\hadoop-3.3.1\bin\wi_君问归期魏有期的博客-CSDN博客 q…...

【Node.js】Express-Generator:快速生成Express应用程序的利器

在Node.js世界中&#xff0c;Express是一个广泛使用的、强大的Web应用程序框架。它为开发者提供了一系列的工具和选项&#xff0c;使得创建高效且可扩展的Web应用程序变得轻而易举。然而&#xff0c;对于初学者来说&#xff0c;配置和初始化Express应用程序可能会有些困难。为了…...

SpringMVC的工作流程及入门

目录 一、概述 ( 1 ) 是什么 ( 2 ) 作用 二、工作流程 ( 1 ) 流程 ( 2 ) 步骤 三、入门实例 ( 1 ) 入门实例 ( 2 ) 静态资源处理 给我们带来的收获 一、概述 ( 1 ) 是什么 SpringMVC是一个基于Java的Web应用开发框架&#xff0c;它是Spring Framework的一部…...

logging.level的含义及设置 【java 日志 (logback、log4j)】

日志级别 trace<debug<info<warn<error<fatal 常用的有&#xff1a;debug&#xff0c;info&#xff0c;warn&#xff0c;error 通常我们想设置日志级别&#xff0c;会用到 logging.level.rootinfo logging.level设置日志级别&#xff0c;后面跟生效的区域。r…...

第 3 章 栈和队列(链栈)

1. 背景说明 链栈是指用单链表实现的栈&#xff0c;其存储结构为链式存储&#xff0c;实现类似于队列的链式实现&#xff0c;不过在插入元素时链栈在头部插入&#xff0c;而 链式队列在尾部插入&#xff0c;本示例中实现为带头结点的链栈&#xff0c;即栈顶元素为栈指针的下一…...

嵌入式面试-经典问题

1、c语言内存模型 2、C语言中的变量定义在什么地方 3、C语言代码如何运行的、关于栈的相关 4、指针函数与函数指针的区分 5、Static关键字的作用 6、const作用 7、进程与线程的区别 8、链表与数组的区别 9、#define宏定义与typedef的区别...

ZLMeidaKit在Windows上启动时:计算机中丢失MSVCR110.dll,以及rtmp推流后无法转换为flv视频流解决

场景 ZLMediaKit在Windows上实现Rtmp流媒体服务器以及模拟rtmp推流和http-flv拉流播放&#xff1a; ZLMediaKit在Windows上实现Rtmp流媒体服务器以及模拟rtmp推流和http-flv拉流播放_zlm流媒体服务器_霸道流氓气质的博客-CSDN博客 按照以上教程启动MediaServer.exe时提示&am…...

项目(智慧教室)第二部分,人机交互页面实现,

使用软件&#xff1a; 1.BmCvtST.exe 这是stm32Cubemx工程下的带三方软件。存在STemWin中。 作用&#xff1a; 图片变成.c文件格式。 2.CodeBlock 3.模拟器工程&#xff08;具体请看上一节&#xff09; 一。emWin环境的搭建 1.codeBlock下载 开源免费。 2.使用stm的C…...

【docker】docker的一些常用命令-------从小白到大神之路之学习运维第92天

目录 一、安装docker-ce 1、从阿里云下载docker-cer.epo源 2、下载部分依赖 3、安装docker 二、启用docker 1、启动docker和不启动查看docker version 2、启动服务查看docker version 有什么区别&#xff1f;看到了吗&#xff1f; 3、看看docker启动后的镜像仓库都有什…...

ubuntu18.04.6的安装教程

目录 一、下载并安装virtualbox virtualbox7.0.8版本的安装 二、Ubuntu的下载与安装 ubuntu18.04.6操作系统 下载 安装 一、下载并安装virtualbox VirtualBox是功能强大的x86和AMD64/Intel64虚拟化企业和家庭使用的产品。VirtualBox不仅是面向企业客户的功能极其丰富的高…...

小白的第一个RNN(情感分析模型)

平台&#xff1a;window10&#xff0c;python3.11.4&#xff0c;pycharm 框架&#xff1a;keras 编写日期&#xff1a;20230903 数据集&#xff1a;英语&#xff0c;自编&#xff0c;训练集和测试集分别有4个样本&#xff0c;标签有积极和消极两种 环境搭建 新建文件夹&am…...

华为云 存在部支持迁移的外键解决方法

DRS 检测出源端存在不支持的外键引用操作 MySQL、GaussDB(for MySQL)为源的全量增量或增量迁移、同步场景&#xff0c;以及MySQL、GaussDB(for MySQL)为源灾备场景 表1 源端存在不支持的外键引用操作 预检查项 源端存在不支持的外键引用操作。 描述 同步对象中存在包含CASC…...

C# winform控件和对象双向数据绑定

实现目的&#xff1a; 控件和对象双向数据绑定 实现结果&#xff1a; 1. 对象值 -> 控件值 2. 控件值 -> 对象值 using System; using System.Windows.Forms;namespace ControlDataBind {public partial class MainForm : Form{People people new People();public Mai…...

达梦8 在CentOS 系统下静默安装

确认系统参数 [rootlocalhost ~]# ulimit -a core file size (blocks, -c) unlimited data seg size (kbytes, -d) unlimited【1048576(即 1GB)以上或 unlimited】 scheduling priority (-e) 0 file size (blocks, -f) unlimite…...

flink k8s sink到kafka报错 Failed to get metadata for topics

可能出现的3种报错 -- 报错1 Failed to get metadata for topics [...]. org.apache.kafka.common.errors.TimeoutException: Call-- 报错2 Caused by: org.apache.kafka.common.errors.TimeoutException: Timed out waiting to send the call. Call: fetchMetadata Heartbe…...

利用大模型MoritzLaurer/mDeBERTa-v3-base-xnli-multilingual-nli-2mil7实现零样本分类

概念 1、零样本分类&#xff1a;在没有样本标签的情况下对文本进行分类。 2、nli:(Natural Language Inference),自然语言推理 3、xnli:(Cross-Lingual Natural Language Inference) ,是一种数据集&#xff0c;支持15种语言&#xff0c;数据集包含10个领域&#xff0c;每个领…...

代码随想录二刷day07

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、力扣454. 四数相加 II二、力扣383. 赎金信三、力扣15. 三数之和四、力扣18. 四数之和 前言 提示&#xff1a;这里可以添加本文要记录的大概内容&#xff1…...

点云从入门到精通技术详解100篇-点云的泊松曲面重建方法

目录 前言 相关理论 2.1三维点云 2.2体素滤波 2.3隐式曲面重建 泊松曲面重建及改进...

【STM32】学习笔记(串口通信)

串口通信 通信接口硬件电路电平标准USARTUSART框图 通信接口 串口是一种应用十分广泛的通讯接口&#xff0c;串口成本低、容易使用、通信线路简单&#xff0c;可实现两个设备的互相通信 单片机的串口可以使单片机与单片机、单片机与电脑、单片机与各式各样的模块互相通信&#…...

【Unity3D赛车游戏优化篇】新【八】汽车实现镜头的流畅跟随,以及不同角度的切换

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;Uni…...

webpack5 (四)

react-cli 中配置 开发环境 const path require(path) const EslintWebpackPlugin require(eslint-webpack-plugin) const HtmlWebpackPlugin require(html-webpack-plugin) const ReactRefreshWebpackPlugin require(pmmmwh/react-refresh-webpack-plugin); //封装处理样…...