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

Spring Boot 整合SpringSecurity和JWT和Redis实现统一鉴权认证

📑前言

本文主要讲了Spring Security文章,如果有什么需要改进的地方还请大佬指出⛺️

🎬作者简介:大家好,我是青衿🥇
☁️博客首页:CSDN主页放风讲故事
🌄每日一句:努力一点,优秀一点

在这里插入图片描述

目录

文章目录

  • 📑前言
  • **目录**
    • 一、介绍
    • 二、主要功能
    • 三、原理
      • 1. SpringSecurity 过滤器链
      • 2. JWT校验登录的校验流程
    • 四、Spring Boot整合Redis、SpringSecurity、JWT的示例demo
  • 📑文章末尾


Spring Security

一、介绍

Spring Security是一个强大且高度可定制的身份验证和访问控制框架。它是保护基于Spring的应用程序的实际标准。Spring Security是一个可以为Java应用程序提供全面安全服务的框架。同时,它也可以轻松扩展以满足自定义需求。

二、主要功能

Authentication (认证),就是用户登录
Authorization (授权):一旦身份验证成功,判断用户拥有什么权限,可以访问什么资源
防止跨站请求伪造(CSRF):Spring Security提供了内置的防护机制,可以防止跨站请求伪造攻击。
密码存储:Spring Security提供了多种密码存储格式,包括明文、加密和哈希。
集成其他安全框架:Spring Security可以与其他安全框架如OAuth2、JWT等进行集成,以提供更全面的安全解决方案。

三、原理

​ SpringSecurity的原理其实就是一个过滤器链,内部包含了提供各种功能的过滤器。

1. SpringSecurity 过滤器链

在这里插入图片描述

SpringSecurity 采用的是责任链的设计模式,它有一条很长的过滤器链。

  • SecurityContextPersistenceFilter:每次请求处理之前将该请求相关的安全上下文信息加载到 SecurityContextHolder 中。
  • LogoutFilter:用于处理退出登录。
  • UsernamePasswordAuthenticationFilter:用于处理基于表单的登录请求,从表单中获取用户名和密码。
  • BasicAuthenticationFilter:检测和处理 http basic 认证。
  • ExceptionTranslationFilter:处理过滤器链中抛出的任何AccessDeniedException和AuthenticationException 。
  • FilterSecurityInterceptor:负责权限校验的过滤器,可以看做过滤器链的出口。

流程说明:客户端发起一个请求,进入 Security 过滤器链。
1.当到 LogoutFilter 的时候判断是否是登出路径,如果是登出路径则到 logoutHandler ,如果登出成功则到logoutSuccessHandler 登出成功处理,如果登出失败则由 ExceptionTranslationFilter ;如果不是登出路径则直接进入下一个过滤器。

2.当到 UsernamePasswordAuthenticationFilter 的时候判断是否为登录路径,如果是,则进入该过滤器进行登录操作,如果登录失败则到 AuthenticationFailureHandler 登录失败处理器处理,如果登录成功则到 AuthenticationSuccessHandler 登录成功处理器处理,如果不是登录请求则不进入该过滤器。

3.当到 FilterSecurityInterceptor 的时候会拿到 uri ,根据 uri 去找对应的鉴权管理器,鉴权管理器做鉴权工作,鉴权成功则到 Controller 层否则到 AccessDeniedHandler 鉴权失败处理器处理。

2. JWT校验登录的校验流程

在这里插入图片描述

首先前端一样是把登录信息发送给后端,后端查询数据库校验用户的账号和密码是否正确,正确的话则使用jwt生成token,并且返回给前端。以后前端每次请求时,都需要携带token,后端获取token后,使用jwt进行验证用户的token是否无效或过期,验证成功后才去做相应的逻辑。

四、Spring Boot整合Redis、SpringSecurity、JWT的示例demo

  1. 添加依赖项在 pom.xml 文件中添加以下依赖项:
   <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version></dependency>
</dependencies>`
  1. 创建Redis配置类
@Configuration
public class RedisConfig {@Value("${spring.redis.host}")private String host;@Value("${spring.redis.port}")private int port;@Beanpublic JedisConnectionFactory jedisConnectionFactory() {return new JedisConnectionFactory(new RedisStandaloneConfiguration(host, port));}@Beanpublic RedisTemplate<String, Object> redisTemplate() {final RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(jedisConnectionFactory());return template;}
}
  1. 创建 JwtTokenUtil 类,用于生成和验证JWT令牌。
@Component
public class JwtTokenUtil implements Serializable {private static final long serialVersionUID = -2550185165626007488L;private static final String secret = "mySecret";public String getUsernameFromToken(String token) {return getClaimFromToken(token, Claims::getSubject);}public Date getExpirationDateFromToken(String token) {return getClaimFromToken(token, Claims::getExpiration);}public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {final Claims claims = getAllClaimsFromToken(token);return claimsResolver.apply(claims);}private Claims getAllClaimsFromToken(String token) {return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();}private Boolean isTokenExpired(String token) {final Date expiration = getExpirationDateFromToken(token);return expiration.before(new Date());}public String generateToken(UserDetails userDetails) {Map<String, Object> claims = new HashMap<>();return doGenerateToken(claims, userDetails.getUsername());}private String doGenerateToken(Map<String, Object> claims, String subject) {return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis())).setExpiration(new Date(System.currentTimeMillis() + 5 * 60 * 60 * 1000)).signWith(SignatureAlgorithm.HS512, secret).compact();}public Boolean validateToken(String token, UserDetails userDetails) {final String username = getUsernameFromToken(token);return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));}
}` 
  1. 创建 JwtAuthenticationEntryPoint 类,用于处理未经授权的请求。
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {private static final long serialVersionUID = -7858869558953243875L;@Overridepublic void commence(HttpServletRequest request, HttpServletResponse response,AuthenticationException authException) throws IOException {response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");}
}` 
  1. 创建 JwtRequestFilter 类,用于解析和验证JWT令牌。
@Component
public class JwtRequestFilter extends OncePerRequestFilter {@Autowiredprivate MyUserDetailsService myUserDetailsService;@Autowiredprivate JwtTokenUtil jwtTokenUtil;@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)throws ServletException, IOException {final String requestTokenHeader = request.getHeader("Authorization");String username = null;String jwtToken = null;if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {jwtToken = requestTokenHeader.substring(7);try {username = jwtTokenUtil.getUsernameFromToken(jwtToken);} catch (IllegalArgumentException e) {System.out.println("Unable to get JWT Token");} catch (ExpiredJwtException e) {System.out.println("JWT Token has expired");}} else {logger.warn("JWT Token does not begin with Bearer String");}if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {UserDetails userDetails = this.myUserDetailsService.loadUserByUsername(username);if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);}}chain.doFilter(request, response);}
}` 
  1. 配置Spring Security
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;@Autowiredprivate UserDetailsService jwtUserDetailsService;@Autowiredprivate JwtRequestFilter jwtRequestFilter;@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Bean@Overridepublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Overrideprotected void configure(HttpSecurity httpSecurity) throws Exception {httpSecurity.csrf().disable().authorizeRequests().antMatchers("/authenticate").permitAll().anyRequest().authenticated().and().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);}
}`

以上是简单的Spring Boot整合Redis、Security、JWT和Redis的示例,可以根据自己的实际需求进行调整。

📑文章末尾

在这里插入图片描述

相关文章:

Spring Boot 整合SpringSecurity和JWT和Redis实现统一鉴权认证

&#x1f4d1;前言 本文主要讲了Spring Security文章&#xff0c;如果有什么需要改进的地方还请大佬指出⛺️ &#x1f3ac;作者简介&#xff1a;大家好&#xff0c;我是青衿&#x1f947; ☁️博客首页&#xff1a;CSDN主页放风讲故事 &#x1f304;每日一句&#xff1a;努力…...

交换机基础(零):交换机基础配置

一、华为设备视图 常用视图 名称 进入视图 视图功能 用户视图 用户从终端成功登录至设备即进 入用户视图&#xff0c;在屏幕上显示 kHuawei> 用户可以完成查看运行状态和统 计信息等功能。在其他视图下 都可使用return直接返回用户视 图 系统视图 在用户视图下&…...

02 线性组合、张成的空间与基

线性组合、张成的空间与基 基向量缩放向量并相加给定向量张成的空间线性相关与线性无关空间的基 这是关于3Blue1Brown "线性代数的本质"的学习笔记。 基向量 当看到一对描述向量的数时&#xff0c;比如[3,-2]时&#xff0c;把这对数中的每个数&#xff08;坐标&…...

解析mfc100u.dll文件丢失的修复方法,快速解决mfc100u.dll问题

在计算机使用过程中&#xff0c;我们经常会遇到一些错误提示&#xff0c;其中最常见的就是“缺少某个文件”的错误。最近&#xff0c;我也遇到了一个这样的问题&#xff0c;那就是“mfc100u.dll丢失”。这个问题可能会导致某些应用程序无法正常运行&#xff0c;给我们带来困扰。…...

免费外文文献检索网站,你一定要知道

01. Sci-Hub 网址链接&#xff1a;https://tool.yovisun.com/scihub/ Sci-hub是一个可以无限搜索、查阅和下载大量优质论文的数据库。其优点在于可以免费下载论文文献。 使用方法&#xff1a; 在Sci—hub搜索栏中粘贴所需文献的网址或者DOI&#xff0c;然后点击右侧的open即可…...

大数据毕业设计选题推荐-收视点播数据分析-Hadoop-Spark-Hive

✨作者主页&#xff1a;IT研究室✨ 个人简介&#xff1a;曾从事计算机专业培训教学&#xff0c;擅长Java、Python、微信小程序、Golang、安卓Android等项目实战。接项目定制开发、代码讲解、答辩教学、文档编写、降重等。 ☑文末获取源码☑ 精彩专栏推荐⬇⬇⬇ Java项目 Python…...

传智杯-21算法赛初赛B组题目详细解法解析-AB题(C/C++、Python、Java)

🚀 欢迎来到 ACM 算法题库专栏 🚀 在ACM算法题库专栏,热情推崇算法之美,精心整理了各类比赛题目的详细解法,包括但不限于ICPC、CCPC、蓝桥杯、LeetCode周赛、传智杯等等。无论您是刚刚踏入算法领域,还是经验丰富的竞赛选手,这里都是提升技能和知识的理想之地。 ✨ 经典…...

post给后端传递数组和多个参数

这是前端的数据结构 data() {return {loading: false,inputForm: {id: ${gridProject.id},gridName: ,gridId: ,projectName: ,projectId: ,type: },data: [],value: []}}, 其中 gridId 和 type 是单个参数 , value 是个数组&#xff0c;注意 这里data中的value[]不要直接给后…...

音频修复增强软件iZotope RX 10 mac中文特点

iZotope RX 10 mac是一款音频修复和增强软件。 iZotope RX 10 mac主要特点 声音修复&#xff1a;iZotope RX 10可以去除不良噪音、杂音、吱吱声等&#xff0c;使音频变得更加清晰干净。 音频增强&#xff1a;iZotope RX 10支持对音频进行音量调节、均衡器、压缩器、限制器等处…...

【面试】虚拟机栈面试题

目录 一、举例栈溢出的情况二、调整栈大小&#xff0c;能保证不出现溢出吗&#xff1f;三、分配的栈内存越大越好吗&#xff1f;四、垃圾回收是否会涉及到虚拟机栈&#xff1f;五、方法中定义的局部变量是否存在线程安全问题&#xff1f;5.1 说明5.2 代码示例 一、举例栈溢出的…...

白话熵增定律

白话熵增定律 热力学中的熵增定律 熵是指一个系统的混乱程度的度量&#xff0c;是热力学中的一个系统的属性。熵增定律是指一个封闭的系统随着时间的发展&#xff0c;在朝平衡状态发展时&#xff0c;其熵会增加&#xff0c;即其越来越混乱。 对于一个房间&#xff0c;如果经常…...

(论文阅读14/100)End-to-end people detection in crowded scenes

文献阅读笔记 简介 题目 End-to-end people detection in crowded scenes 作者 Russell Stewart, Mykhaylo Andriluka 原文链接 https://arxiv.org/pdf/1506.04878.pdf 关键词 Null 研究问题 当前的人员检测器要么以滑动窗口的方式扫描图像&#xff0c;要么对一组离…...

Go的错误处理

什么是错误&#xff1f; 错误表示程序中发生的任何异常情况。假设我们正在尝试打开一个文件&#xff0c;但该文件在文件系统中不存在。这是一种异常情况&#xff0c;表示为错误。 Go 中的错误是普通的旧值。就像任何其他内置类型&#xff08;例如 int、float64 等&#xff09…...

云原生相关概念

云计算 指托管在外部数据中心并按使用量付费提供给用户的软件基础设施。公司不必为昂贵的服务器付费并进行维护。相反&#xff0c;他们可以使用云提供商提供的按需云原生服务&#xff0c;例如存储、数据库和分析。 云原生 是在 云计算环境 中构建、部署和管理现代应用程序的…...

【JS】this指向

一、this指向的四种规则 1.默认绑定规则 默认指向&#xff1a;指向window 独立调用&#xff1a;指向window 对象指向&#xff0c;比较的是引用地址。 console.log(this window); //true console.log({} {}); //false //函数的独立调用 function test(){console.lo…...

SpringCloud Alibaba Demo(Nacos,OpenFeign,Gatway,Sentinel)

开源地址&#xff1a; ma/springcloud-alibaba-demo 简介 参考&#xff1a;https://www.cnblogs.com/zys2019/p/12682628.html SpringBoot、SpringCloud 、SpringCloud Alibaba 以及各种组件存在版本对应关系。可参考下面 版本对应 项目前期准备 启动nacos. ./startup.c…...

基于nodejs+vue畅听校园点歌系统的设计与实现

目 录 摘 要 I ABSTRACT II 目 录 II 第1章 绪论 1 1.1背景及意义 1 1.2 国内外研究概况 1 1.3 研究的内容 1 第2章 相关技术 3 2.1 nodejs简介 4 2.2 express框架介绍 6 2.4 MySQL数据库 4 第3章 系统分析 5 3.1 需求分析 5 3.2 系统可行性分析 5 3.2.1技术可行性&#xff1a;…...

IDEA 设置代码注释模板

功能简介&#xff1a; 每次看别人代码时&#xff0c;面对毫无注释的类&#xff0c;除了头大还是头大&#xff0c; 以下提供了一种代码类注释模板 新建java类的时候&#xff0c;自动增加类注释&#xff0c;养成代码开发好习惯 效果展示&#xff1a; 代码模板&#xff1a; #if (…...

emoji对齐 特殊字符对齐 文本对齐

emoji如何对齐 特殊字符如何对齐 高级文本对齐 问题引出 我们在程序打印输出时&#xff0c;如何我们所输出的字符中包含emoji文本&#xff0c;或者其它特殊的字符文本&#xff0c;则我们的打印对齐效果将出现错位。以下代码复现了这一效果&#xff08;tips&#xff1a; 马老师…...

Selenium Python 中的动作链

Selenium 是一个用于自动化的独立的基于 Web 的工具。 它是任何人都可以使用的开源工具。 与Python语言结合使用该工具进行测试。 操作链是 Selenium 的基本组成部分&#xff0c;提供了一种管理低级交互的方法&#xff0c;例如按键、鼠标移动、鼠标按钮操作以及与上下文菜单的…...

OceanBase:03-集群部署

目录 一、集群规划 二、配置要求 三、部署前配置 1.配置 limits.conf 2.配置 sysctl.conf 3.关闭防火墙 4.关闭 SELinux 5.创建数据目录&#xff0c;修改文件所有者信息 6.设置无密码 SSH 登录 7.安装jdk 四、解压执行安装 五、集群部署 1.OBD命令行部署 2. OBD白…...

PTA: 矩阵的乘法运算

矩阵的乘法运算 题目输入格式输出格式输入样例输出样例 代码 题目 线性代数中的矩阵可以表示为一个row&#xff0a;column的二维数组&#xff0c;当row和column均为1时&#xff0c;退化为一个数&#xff0c;当row为1时&#xff0c;为一个行向量&#xff0c;当column为1时&…...

4K Video Downloader Pro v4.28.0(视频下载器)

4K Video Downloader Pro是一款专业的视频下载软件&#xff0c;支持从YouTube、Vimeo、Facebook、Instagram、TikTok等主流视频网站下载高质量的4K、HD和普通视频。它的操作流程简单&#xff0c;只需复制视频链接并粘贴到软件中即可开始下载。此外&#xff0c;该软件还提供了多…...

java pdf,word,ppt转图片

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

map set

目录 一、关联式容器 二、键值对 三、树形结构的关联式容器 3.1 set 3.1.1 set的介绍 3.1.2 set的使用 3.2 multiset 3.2.1 multiset的介绍 3.2.2 multiset的使用 3.3 map 3.3.1 map的介绍 3.3.2 map的使用 …...

Fourier分析导论——第3章——Fourier级数的收敛性(E.M. Stein R. Shakarchi)

第 3 章 Fourier级数的收敛性(Convergence of Fourier Series) The sine and cosine series, by which one can represent an arbitrary function in a given interval, enjoy among other remarkable properties that of being convergent. This property did not escape…...

解决ruoyi-vue部署到域名子路径静态资源404

参考ruoyi前端手册...

游戏引擎中为什么要用四元数表示旋转而不用欧拉角旋转?

个人观点&#xff0c;仅供参考&#xff0c;如有错误可太刺激了 四元数的简单概念和使用 欧拉角通常用于表示一个物体的旋转状态&#xff0c;而不是表示旋转过程。 欧拉角描述的是物体相对于某个参考坐标系的朝向或旋转状态&#xff0c;通常以不同的轴&#xff08;例如&#x…...

E-Office(泛微OA)前台任意文件读取漏洞复现

简介 泛微E-Office是一款企业级的全流程办公自动化软件&#xff0c;它包括协同办公、文档管理、知识管理、工作流管理等多个模块&#xff0c;涵盖了企业日常工作中的各个环节。在该产品前台登录页存在文件读取漏洞。 officeserver.php文件存在任意文件读取漏洞&#xff0c;通…...

前端小案例 | 喵喵大王立大功 | 一个带便利贴功能的todolist面板

文章目录 &#x1f4da;html&#x1f4da;css&#x1f4da;js&#x1f407;stickynote.js&#x1f407;todolist.js&#x1f407;clock.js &#x1f4da;html <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><m…...