当前位置: 首页 > 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…...

别再混淆了!一文讲透NvDecoder里ulNumDecodeSurfaces和ulNumOutputSurfaces到底怎么用

深入解析NvDecoder&#xff1a;解码缓存与输出缓存的本质区别与实战配置 在视频处理领域&#xff0c;NVIDIA的硬件解码器&#xff08;NVDEC&#xff09;因其出色的性能和高效的资源利用率而广受开发者青睐。然而&#xff0c;对于许多中高级开发者来说&#xff0c;NvDecoder中ul…...

实战指南:基于快马平台与Playwright打造自动化的网站内容监测应用

今天想和大家分享一个非常实用的自动化监测方案——基于Playwright和InsCode(快马)平台搭建的新闻网站更新监测系统。这个项目特别适合需要追踪行业动态或竞品资讯的朋友&#xff0c;整个过程不需要复杂的服务器配置&#xff0c;用快马平台就能轻松实现部署和定时运行。 项目背…...

如何快速搭建QQ机器人:OpenShamrock的终极指南

如何快速搭建QQ机器人&#xff1a;OpenShamrock的终极指南 【免费下载链接】OpenShamrock A Bot Framework based on Xposed with OneBot11 项目地址: https://gitcode.com/gh_mirrors/op/OpenShamrock OpenShamrock是一款基于LSPosed框架实现的QQ机器人开发框架&#x…...

Windows系统优化工具WinUtil:从新手到专家的完整使用指南

Windows系统优化工具WinUtil&#xff1a;从新手到专家的完整使用指南 【免费下载链接】winutil Chris Titus Techs Windows Utility - Install Programs, Tweaks, Fixes, and Updates 项目地址: https://gitcode.com/GitHub_Trending/wi/winutil 你是否厌倦了Windows系统…...

ESP32智能硬件开发实战指南:从环境搭建到AI功能落地

ESP32智能硬件开发实战指南&#xff1a;从环境搭建到AI功能落地 【免费下载链接】xiaozhi-esp32 An MCP-based chatbot | 一个基于MCP的聊天机器人 项目地址: https://gitcode.com/GitHub_Trending/xia/xiaozhi-esp32 如何在复杂的硬件开发中快速实现AI功能集成&#xf…...

PaddleNLP:面向产业级应用的大语言模型全流程开发套件技术深度解析

PaddleNLP&#xff1a;面向产业级应用的大语言模型全流程开发套件技术深度解析 【免费下载链接】PaddleNLP PaddleNLP是一款基于飞桨深度学习框架的大语言模型(LLM)开发套件&#xff0c;支持在多种硬件上进行高效的大模型训练、无损压缩以及高性能推理。PaddleNLP 具备简单易用…...

Fiji在macOS系统的兼容性解决方案:从启动故障到配置优化的完整指南

Fiji在macOS系统的兼容性解决方案&#xff1a;从启动故障到配置优化的完整指南 【免费下载链接】fiji A "batteries-included" distribution of ImageJ :battery: 项目地址: https://gitcode.com/gh_mirrors/fi/fiji Fiji作为科学图像处理领域广泛使用的"…...

抗DDoS设备性能测试方法详解:专业仪表如何精准评估防护能力

摘要抗DDoS设备的防护效果如何&#xff0c;单靠厂商自测数据不可信&#xff0c;需要专业网络安全测试仪表进行第三方验证。本文系统梳理SYN Flood、UDP Flood、HTTP Flood、反射放大、慢速攻击等主流DDoS攻击的测试方法&#xff0c;结合运营商级集采测试标准&#xff0c;详解清…...

translategemma-4b-it快速入门:Ollama部署图文翻译模型,开箱即用

translategemma-4b-it快速入门&#xff1a;Ollama部署图文翻译模型&#xff0c;开箱即用 1. 认识translategemma-4b-it 1.1 什么是translategemma-4b-it translategemma-4b-it是Google基于Gemma 3架构开发的开源多模态翻译模型。与普通翻译工具不同&#xff0c;它不仅能处理…...

如何高效保存B站视频?全功能跨平台工具BiliTools使用指南

如何高效保存B站视频&#xff1f;全功能跨平台工具BiliTools使用指南 【免费下载链接】BiliTools A cross-platform bilibili toolbox. 跨平台哔哩哔哩工具箱&#xff0c;支持下载视频、番剧等等各类资源 项目地址: https://gitcode.com/GitHub_Trending/bilit/BiliTools …...