spring security与gateway结合进行网关鉴权和授权
在Spring Cloud Gateway中集成Spring Security 6以实现鉴权和认证工作,可以在网关代理层完成权限校验和认证。这种架构通常被称为“边缘安全”或“API网关安全”,它允许你在请求到达后端服务之前进行集中式的安全控制。
以下是如何配置Spring Cloud Gateway与Spring Security 6来实现这一目标的详细步骤:
1. 添加依赖
首先,确保你的项目中包含必要的依赖。你需要Spring Security、Spring Cloud Gateway以及JWT相关的依赖。
<dependencies><!-- Spring Boot Starter Security --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><!-- Spring Cloud Gateway --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency><!-- JWT Support --><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-api</artifactId><version>0.11.5</version></dependency><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-impl</artifactId><version>0.11.5</version><scope>runtime</scope></dependency><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt-jackson</artifactId><version>0.11.5</version><scope>runtime</scope></dependency><!-- Spring Cloud Dependencies Management --><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>2022.0.0</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>
</dependencies>
2. 配置SecurityFilterChain
在Spring Security配置类中设置SecurityFilterChain,以支持基于Token的认证机制,并应用到Gateway路由上。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.authentication.AuthenticationWebFilter;
import reactor.core.publisher.Mono;@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {@Beanpublic SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http, JwtAuthenticationManager jwtAuthenticationManager) {http.csrf().disable() // 禁用CSRF保护.authorizeExchange(exchanges -> exchanges.pathMatchers("/login").permitAll() // 公开路径,例如登录.anyExchange().authenticated() // 其他所有请求都需要认证).addFilterAt(jwtAuthenticationFilter(jwtAuthenticationManager), AuthenticationWebFilter.class);return http.build();}@Beanpublic MapReactiveUserDetailsService userDetailsService() {UserDetails userDetails = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build();return new MapReactiveUserDetailsService(userDetails);}private AuthenticationWebFilter jwtAuthenticationFilter(JwtAuthenticationManager jwtAuthenticationManager) {AuthenticationWebFilter filter = new AuthenticationWebFilter(jwtAuthenticationManager);filter.setServerAuthenticationConverter(new BearerTokenServerAuthenticationConverter());return filter;}
}
3. 实现JWT工具类
创建一个工具类来生成和解析JWT令牌。
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;@Component
public class JwtUtil {private String secret = "yourSecretKey"; // 应该存储在一个安全的地方,并且不要硬编码public Mono<String> extractUsername(String token) {return Mono.just(extractClaim(token, Claims::getSubject));}public Date extractExpiration(String token) {return extractClaim(token, Claims::getExpiration);}public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {final Claims claims = extractAllClaims(token);return claimsResolver.apply(claims);}private Claims extractAllClaims(String token) {return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();}private Boolean isTokenExpired(String token) {return extractExpiration(token).before(new Date());}public Mono<String> generateToken(UserDetails userDetails) {Map<String, Object> claims = new HashMap<>();return Mono.just(createToken(claims, userDetails.getUsername()));}private String createToken(Map<String, Object> claims, String subject) {return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis())).setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)) // 10小时过期.signWith(SignatureAlgorithm.HS256, secret).compact();}public Mono<Boolean> validateToken(String token, UserDetails userDetails) {final String username = extractUsername(token).block();return Mono.just(username.equals(userDetails.getUsername()) && !isTokenExpired(token));}
}
4. 实现JWT认证管理器
创建一个自定义的认证管理器来处理JWT验证逻辑。
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;@Component
public class JwtAuthenticationManager implements ReactiveAuthenticationManager {private final JwtUtil jwtUtil;private final UserDetailsService userDetailsService;public JwtAuthenticationManager(JwtUtil jwtUtil, UserDetailsService userDetailsService) {this.jwtUtil = jwtUtil;this.userDetailsService = userDetailsService;}@Overridepublic Mono<Authentication> authenticate(Authentication authentication) {String token = (String) authentication.getCredentials();return jwtUtil.extractUsername(token).flatMap(username -> {if (jwtUtil.validateToken(token, userDetailsService.loadUserByUsername(username)).block()) {UserDetails userDetails = userDetailsService.loadUserByUsername(username);return Mono.just(new UsernamePasswordAuthenticationToken(userDetails, token, userDetails.getAuthorities()));} else {return Mono.empty();}});}
}
5. 实现Bearer Token转换器
创建一个转换器来从请求头中提取Bearer Token。
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;public class BearerTokenServerAuthenticationConverter implements ServerAuthenticationConverter {@Overridepublic Mono<org.springframework.security.oauth2.server.resource.authentication.ServerAuthenticationToken> convert(ServerWebExchange exchange) {String authHeader = exchange.getRequest().getHeaders().getFirst("Authorization");if (authHeader != null && authHeader.startsWith("Bearer ")) {String token = authHeader.substring(7);return Mono.just(new org.springframework.security.oauth2.server.resource.authentication.ServerAuthenticationToken(token, token));}return Mono.empty();}
}
6. 配置Gateway路由
最后,在你的网关配置文件中定义路由。
spring:cloud:gateway:routes:- id: service_routeuri: lb://your-backend-servicepredicates:- Path=/api/**filters:- RewritePath=/api/(?<segment>.*), /$\{segment}
总结
通过上述步骤,你可以在Spring Cloud Gateway中集成Spring Security 6,从而实现在网关代理层进行鉴权和认证的功能。主要步骤包括:
- 添加依赖:引入必要的依赖。
- 配置SecurityFilterChain:禁用CSRF保护并设置为无状态会话。
- 实现JWT工具类:用于生成和解析JWT令牌。
- 实现JWT认证管理器:处理JWT验证逻辑。
- 实现Bearer Token转换器:从请求头中提取Bearer Token。
- 配置Gateway路由:定义路由规则。
这样,你的应用程序就可以使用JWT在网关层进行安全认证和授权了。
相关文章:
spring security与gateway结合进行网关鉴权和授权
在Spring Cloud Gateway中集成Spring Security 6以实现鉴权和认证工作,可以在网关代理层完成权限校验和认证。这种架构通常被称为“边缘安全”或“API网关安全”,它允许你在请求到达后端服务之前进行集中式的安全控制。 以下是如何配置Spring Cloud Gat…...
LabVIEW在电机自动化生产线中的实时数据采集与生产过程监控
在电机自动化生产线中,实时数据采集与生产过程监控是确保生产效率和产品质量的重要环节。LabVIEW作为一种强大的图形化编程平台,可以有效实现数据采集、实时监控和自动化控制。详细探讨如何利用LabVIEW实现这一目标,包括硬件选择、软件架构设…...
log4j2日志配置文件
log4j2配置文件每个项目都会用到,记录一个比较好用的配置文件,方便以后使用时调取,日志输出级别为debug,也可以修改 <?xml version"1.0" encoding"UTF-8"?> <Configuration monitorInterval"180" packages""><prope…...
用Deepseek做EXCLE文件对比
背景是我想对比两个PO系统里的一个消息映射,EDI接口的mapping有多复杂懂的都懂,它还不支持跨系统版本对比,所以我费半天劲装NWDS,导出MM到excle,然后问题来了,我需要对比两个excel文件里的内容,…...
Tailwind CSS v4.0 升级与 Astro 5.2 项目迁移记录
本文博客链接 https://ysx.cosine.ren/tailwind-update-v4-migrate 自用小记。 Tailwind CSS v4.0 - Tailwind CSS 新的高性能引擎 - 完整构建的速度速度快 5 倍,增量构建的速度快于 100 倍以上 —— 以微秒为单位进行测量。为现代 Web 设计 - 建立在前沿的 CSS 特…...
TongSearch3.0.4.0安装和使用指引(by lqw)
文章目录 安装准备手册说明支持的数据类型安装控制台安装单节点(如需集群请跳过这一节)解压和启动开启X-Pack Security和生成p12证书(之后配置内置密码和ssl要用到)配置内置用户密码配置ssl(先配置内置用户密码再配ssl)配置控制台…...
低代码产品表单渲染架构
在React和Vue没有流行起来的时候,低代码产品的表单渲染设计通常会使用操作Dom的方式实现。 下面是一个表单的例子: 产品层 用户通过打开表单,使用不同业务场景业务下的表单页面,中间的Render层就是技术实现。 每一个不同业务的表单…...
windows 剪切板的写入、读取,包括图片,文本内容
介绍 在windows开发过程中,我们可能会需要对系统剪切板进行操作,其中包括读取剪切板数据和将数据写入到剪切板中 设置剪切板内容 /*** brief 设置剪切板内容* param[in] pszData 指向缓冲区的指针* param[in] nDataLen 缓冲区长度* return 成功返回TRU…...
Matplotlib 高级图表绘制与交互式可视化(mpld3)
我们先重新回忆一下它的主要作用: 一、Matplotlib 简介 Matplotlib 是 Python 中一个非常强大的可视化库,广泛用于数据可视化、科学计算和工程领域。它提供了丰富的绘图功能,可以生成各种静态、动态和交互式的图表。以下是 Matplotlib 的主要功能及其详细讲解。 二、基本…...
(9)gdb 笔记(2):查看断点 info b,删除断点 delete 3,回溯 bt,
(11) 查看断点 info b: # info b举例: (12)删除断点 delete 2 或者删除所有断点: # 1. 删除指定的断点 delete 3 # 2. 删除所有断点 delete 回车,之后输入 y 确认删除所有断点 举…...
专业学习|通过案例了解蒙特卡罗模拟实操步骤与含义
一、蒙特卡罗模拟介绍 蒙特卡罗模拟(Monte Carlo Simulation)是一种基于随机采样的数值计算方法,用于解决具有不确定性或复杂概率分布的问题。其核心思想是通过多次随机抽样来逼近系统的行为或目标函数的真实值,进而对系统进行评估…...
云端智慧:创业公司如何以全球视野选择最佳平台,实现业务新高度
2016年8月,一个名叫Bryce Adams的人辞去了自己原本很稳定的工作,开始追逐梦想:为使用WooCommerce(一种开源的WordPress数字商务插件)的公司开发一种能提供各类报表解决方案的应用。为此他成立了Metorik公司ÿ…...
【工具变量】中国省级八批自由贸易试验区设立及自贸区设立数据(2024-2009年)
一、测算方式:参考C刊《中国软科学》任晓怡老师(2022)的做法,使用自由贸易试验区(Treat Post) 表征,Treat为个体不随时间变化的虚拟变量,如果该城市设立自由贸易试验区则赋值为1,反之赋值为0&am…...
猫眼Java开发面试题及参考答案(上)
详细介绍项目,像项目中如何用 Redis,用到 Redis 哪些数据类型,项目中遇到哪些问题,怎么解决的 在我参与的一个电商项目中,Redis 发挥了至关重要的作用。这个电商项目主要是为用户提供商品浏览、购物车管理、订单处理等一系列功能。 在项目中使用 Redis 主要是为了提升系统…...
WSL2中安装的ubuntu开启与关闭探讨
1. PC开机后,查询wsl状态 在cmd或者powersell中输入 wsl -l -vNAME STATE VERSION * Ubuntu Stopped 22. 从windows访问WSL2 wsl -l -vNAME STATE VERSION * Ubuntu Stopped 23. 在ubuntu中打开一个工作区后…...
Linux抢占式内核:技术演进与源码解析
一、引言 Linux内核作为全球广泛使用的开源操作系统核心,其设计和实现一直是计算机科学领域的研究热点。从早期的非抢占式内核到2.6版本引入的抢占式内核,Linux在实时性和响应能力上取得了显著进步。本文将深入探讨Linux抢占式内核的引入背景、技术实现以及与非抢占式内核的…...
【Numpy核心编程攻略:Python数据处理、分析详解与科学计算】2.28 NumPy+Matplotlib:科学可视化的核心引擎
2.28 NumPyMatplotlib:科学可视化的核心引擎 目录 #mermaid-svg-KTB8Uqiv5DLVJx7r {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-KTB8Uqiv5DLVJx7r .error-icon{fill:#552222;}#mermaid-svg-KTB8Uqiv5…...
C#面试常考随笔12:游戏开发中常用的设计模式【C#面试题(中级篇)补充】
C#面试题(中级篇),详细讲解,帮助你深刻理解,拒绝背话术!-CSDN博客 简单工厂模式 优点: 根据条件有工厂类直接创建具体的产品 客户端无需知道具体的对象名字,可以通过配置文件创建…...
【深度学习入门_机器学习理论】朴素贝叶斯(NaiveBayes)
本部分主要为机器学习理论入门_熟悉朴素贝叶斯算法,书籍参考 “ 统计学习方法(第二版)”。 学习目标: 熟悉条件概率、先验概率、后验概率、全概率,熟悉朴素贝叶斯算法原理与推判断过程;熟悉参数估计&#…...
docker pull Error response from daemon问题
里面填写 里面解决方案就是挂代理。 以虚拟机为例,将宿主机配置端口设置,https/http端口设为7899 配置虚拟机的http代理: vim /etc/systemd/system/docker.service.d/http-proxy.conf里面填写,wq保存 [Service] Environment…...
测试微信模版消息推送
进入“开发接口管理”--“公众平台测试账号”,无需申请公众账号、可在测试账号中体验并测试微信公众平台所有高级接口。 获取access_token: 自定义模版消息: 关注测试号:扫二维码关注测试号。 发送模版消息: import requests da…...
Cursor实现用excel数据填充word模版的方法
cursor主页:https://www.cursor.com/ 任务目标:把excel格式的数据里的单元格,按照某一个固定模版填充到word中 文章目录 注意事项逐步生成程序1. 确定格式2. 调试程序 注意事项 直接给一个excel文件和最终呈现的word文件的示例,…...
linux之kylin系统nginx的安装
一、nginx的作用 1.可做高性能的web服务器 直接处理静态资源(HTML/CSS/图片等),响应速度远超传统服务器类似apache支持高并发连接 2.反向代理服务器 隐藏后端服务器IP地址,提高安全性 3.负载均衡服务器 支持多种策略分发流量…...
3.3.1_1 检错编码(奇偶校验码)
从这节课开始,我们会探讨数据链路层的差错控制功能,差错控制功能的主要目标是要发现并且解决一个帧内部的位错误,我们需要使用特殊的编码技术去发现帧内部的位错误,当我们发现位错误之后,通常来说有两种解决方案。第一…...
Java多线程实现之Callable接口深度解析
Java多线程实现之Callable接口深度解析 一、Callable接口概述1.1 接口定义1.2 与Runnable接口的对比1.3 Future接口与FutureTask类 二、Callable接口的基本使用方法2.1 传统方式实现Callable接口2.2 使用Lambda表达式简化Callable实现2.3 使用FutureTask类执行Callable任务 三、…...
ServerTrust 并非唯一
NSURLAuthenticationMethodServerTrust 只是 authenticationMethod 的冰山一角 要理解 NSURLAuthenticationMethodServerTrust, 首先要明白它只是 authenticationMethod 的选项之一, 并非唯一 1 先厘清概念 点说明authenticationMethodURLAuthenticationChallenge.protectionS…...
SpringTask-03.入门案例
一.入门案例 启动类: package com.sky;import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCach…...
A2A JS SDK 完整教程:快速入门指南
目录 什么是 A2A JS SDK?A2A JS 安装与设置A2A JS 核心概念创建你的第一个 A2A JS 代理A2A JS 服务端开发A2A JS 客户端使用A2A JS 高级特性A2A JS 最佳实践A2A JS 故障排除 什么是 A2A JS SDK? A2A JS SDK 是一个专为 JavaScript/TypeScript 开发者设计的强大库ÿ…...
BLEU评分:机器翻译质量评估的黄金标准
BLEU评分:机器翻译质量评估的黄金标准 1. 引言 在自然语言处理(NLP)领域,衡量一个机器翻译模型的性能至关重要。BLEU (Bilingual Evaluation Understudy) 作为一种自动化评估指标,自2002年由IBM的Kishore Papineni等人提出以来,…...
淘宝扭蛋机小程序系统开发:打造互动性强的购物平台
淘宝扭蛋机小程序系统的开发,旨在打造一个互动性强的购物平台,让用户在购物的同时,能够享受到更多的乐趣和惊喜。 淘宝扭蛋机小程序系统拥有丰富的互动功能。用户可以通过虚拟摇杆操作扭蛋机,实现旋转、抽拉等动作,增…...
