开发自定义starter
环境:Spring Cloud Gateway
需求:防止用户绕过网关直接访问服务器,用户只需引入依赖即可。
1、创建项目
首先创建一个spring boot项目
2、配置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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.15</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>io.github.lanxiu-code</groupId><artifactId>security-spring-boot-starter</artifactId><version>1.0.0</version><name>security-spring-boot-starter</name><description>security-spring-boot-starter</description><url>https://github.com/lanxiu-code/security-spring-boot-starter</url><licenses><license><name>The Apache Software License, Version 2.0</name><url>http://www.apache.org/licenses/LICENSE-2.0.txt</url></license></licenses><developers><developer><id>lanxiu</id><name>lanxiu</name><email>3403138527@qq.com</email><roles><role>Project Manager</role><role>Architect</role></roles></developer></developers><scm><connection>https://github.com/lanxiu-code/security-spring-boot-starter.git</connection><developerConnection>scm:git:ssh://git@github.com:lanxiu-code/security-spring-boot-starter.git</developerConnection><url>https://github.com/lanxiu-code/security-spring-boot-starter</url></scm><properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- 提供了自动装配功能--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency></dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><source>${java.version}</source><target>${java.version}</target></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><skip>true</skip></configuration></plugin><!-- central发布插件 --><plugin><groupId>org.sonatype.central</groupId><artifactId>central-publishing-maven-plugin</artifactId><version>0.4.0</version><extensions>true</extensions><configuration><publishingServerId>lanxiu</publishingServerId><tokenAuth>true</tokenAuth></configuration></plugin><!-- source源码插件 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-source-plugin</artifactId><executions><execution><id>attach-sources</id><goals><goal>jar-no-fork</goal></goals></execution></executions></plugin><!-- javadoc插件 --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-javadoc-plugin</artifactId><version>2.9.1</version><executions><execution><id>attach-javadocs</id><goals><goal>jar</goal></goals></execution></executions></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-gpg-plugin</artifactId><version>1.6</version><configuration><executable>D:\software\GPG\GnuPG\bin\gpg.exe</executable><keyname>lanxiu-code</keyname></configuration><executions><execution><id>sign-artifacts</id><phase>verify</phase><goals><goal>sign</goal></goals></execution></executions></plugin></plugins></build></project>
- spring-boot-configuration-processor:给用户提示配置
- spring-boot-autoconfigure:自动装配功能
3、配置yml
spring:application:name: security-spring-boot-startersecurity:gateway:only-gateway: true# 认证字段auth-key: auth# 认证值auth-value: gateway
4、SecurityConfig配置类
package com.lx.security.config;import com.lx.security.constant.SecurityConstant;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;@Data
@Configuration
@ConfigurationProperties(prefix = "security.gateway")
public class SecurityConfig {/** 是否只能通过网关请求服务器* */private Boolean onlyGateway = Boolean.TRUE;/** 认证字段* */private String authKey = SecurityConstant.AUTH_KEY;/** 认证值* */private String authValue = SecurityConstant.AUTH_VALUE;
}
5、ServerProtectInterceptor拦截器
package com.lx.security.interceptor;import com.lx.security.config.SecurityConfig;
import com.lx.security.constant.SecurityConstant;
import com.lx.security.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;@Component
@Slf4j
public class ServerProtectInterceptor implements HandlerInterceptor {@Resourceprivate SecurityConfig securityConfig;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {if (!securityConfig.getOnlyGateway()){return true;}String auth = request.getHeader(securityConfig.getAuthKey());if(securityConfig.getAuthValue().equals(auth)){return true;}else{//String result = "{\"code\":403,\"data\":null,\"message\":\"非法请求\"}";WebUtils.render(response, HttpStatus.FORBIDDEN.value());return false;}}}
WebRequestInterceptor 和 HandlerInterceptor 都是 Spring 框架提供的拦截器机制的一部分,但它们在使用场景和生命周期上有一定的区别:
- 应用范围:
- WebRequestInterceptor 是一个更通用的拦截器接口,它可以应用于任何类型的请求(如 HTTP 请求)。
- HandlerInterceptor 则专门用于 Web MVC 应用中的控制器方法调用前后。
- 生命周期:
- WebRequestInterceptor 的方法包括 preHandle, postHandle 和 afterCompletion,但它的 preHandle 方法是在请求处理之前调用,而 postHandle 和 afterCompletion 则分别在请求处理之后和视图渲染之后调用。
- HandlerInterceptor 同样有 preHandle, postHandle 和 afterCompletion 方法,但是这些方法更加专注于 MVC 控制器的生命周期管理。
6、WebMvcConfig配置拦截器
package com.lx.security.config;import com.lx.security.interceptor.ServerProtectInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Resourceprivate ServerProtectInterceptor serverProtectInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(serverProtectInterceptor);}
}
7、SecurityAutoConfiguration自动装配类
package com.lx.security;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;@Configuration
@ComponentScan("com.lx.security")
@ConditionalOnProperty(prefix = "security.gateway", name = "only-gateway", havingValue = "true")
@EnableConfigurationProperties
public class SecurityAutoConfiguration {}
@ConditionalOnProperty注解,它的作用是根据某个条件类决定是否自动配置,例如上面的意思是如果only-gateway和havingValue的值相同就会加载配置,否则不加载,如果配置了matchIfMissing = true,即使没有配置yml也会加载配置。
但是这个@ConditionalOnProperty注解有个坑,花了我一天才解决:
项目中的配置名称必须和条件注解@ConditionalOnProperty中的name一致。如果@ConditionalOnProperty中的name是驼峰的话(onlyGateway),项目中的配置名也要用驼峰,不能用-。
反之如果@ConditionalOnProperty中的name是用-的话(only-gateway),项目中的配置名可以用驼峰,也可以用-。
也可以直接选择不用@ConditionalOnProperty注解
上面两个图就会导致自动装配不生效,因为onlyGateway和only-gateway不相等
8、配置spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.lx.security.SecurityAutoConfiguration
如果是SpringBoot3版本要在
METE-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports中配置自动配置
com.lx.security.SecurityAutoConfiguration
9、打包
maven install
10、引入项目
<!-- 安全认证依赖 -->
<dependency><groupId>com.lx.security</groupId><artifactId>security-spring-boot-starter</artifactId><version>1.0.0</version>
</dependency>
引入项目后配置好yml即可使用
相关文章:

开发自定义starter
环境:Spring Cloud Gateway 需求:防止用户绕过网关直接访问服务器,用户只需引入依赖即可。 1、创建项目 首先创建一个spring boot项目 2、配置pom.xml <?xml version"1.0" encoding"UTF-8"?> <project xm…...

Vue2电商平台(五)、加入购物车,购物车页面
文章目录 一、加入购物车1. 添加到购物车的接口2. 点击按钮的回调函数3. 请求成功后进行路由跳转(1)、创建路由并配置路由规则(2)、路由跳转并传参(本地存储) 二、购物车页面的业务1. uuid生成用户id2. 获取购物车数据3. 计算打勾商品总价4. 全选与商品打勾(1)、商品全部打勾&a…...

众数信科 AI智能体政务服务解决方案——寻知智能笔录系统
政务服务解决方案 寻知智能笔录方案 融合民警口供录入与笔录生成需求 2分钟内生成笔录并提醒错漏 助办案人员二次询问 提升笔录质量和效率 寻知智能笔录系统 众数信科AI智能体 产品亮点 分析、理解行业知识和校验规则 AI实时提醒用户文书需注意部分 全文校验格式、内容…...

Redis篇(面试题 - 连环16炮)(持续更新迭代)
目录 目录 目录 (第一炮)一、Redis?常用数据结构? 1. 项目里面到了Redis,为什么选用Redis? 2. Redis 是什么? 3. Redis和关系型数据库的本质区别有哪些? 4. Redis 的线程模型…...
selenium元素定位
find_element和find_elements 元素定位有两个表达式,分别为find_element()和find_elements(),它们的不同点如下: find_element():找出的为单个元素,若有多个元素为同一表达式,则默认定位第一个元素&#…...

美畅物联丨视频汇聚从“设”开始:海康威视摄像机设置详解
在运用畅联云平台进行视频汇聚与监控管理时,海康威视的安防摄像机凭借其卓越的性能与广泛的应用兼容性,成为了众多用户的首选产品。海康威视摄像机参数设置与调试对于实现高效的安防监控至关重要。今天,让我们一同深入学习海康摄像机的参数设…...
聊天机器人羲和的代码04
进一步完善和优化聊天机器人GUI,使其更加丰富和美观,采取了以下措施: 添加图标:为应用程序添加一个图标。 调整布局:进一步优化布局,使其更加美观。 增加样式:使用更多的样式和主题来提升视觉效果。 添加动画:增加加载动画以提高用户体验。 优化控件:使用更现代的控件…...

Linux安装配置Jupyter Lab并开机自启
文章目录 1、安装配置jupyter lab首先需要使用pip3安装:生成配置文件和密码: 2、设置开机自启首先通过which jupyter查询到可执行文件路径:设置自启服务: 1、安装配置jupyter lab 首先需要使用pip3安装: pip3 instal…...
Java基础——`UUID.randomUUID()` 方法详细介绍
这里写自定义目录标题 UUID.randomUUID() 方法详细介绍1. 概述2. UUID 的结构与格式UUID 的 128 位结构划分: 3. UUID.randomUUID() 方法详解3.1 方法签名3.2 使用示例3.3 生成原理3.4 随机数生成的范围3.5 随机字符的取值范围 4. UUID 的版本与特性4.1 UUID 版本 4…...
前端面试常见手写代码题【详细篇】
文章目录 前言:防抖节流函数柯里化函数组合instanceof 实现实现new操作符的行为深拷贝继承实现:手写Promise数组中常见函数的实现 前言: 在前端面试中,经常会遇到要求手写的代码的题目,主要是考察我们的编程能力、和对…...

当代最厉害的哲学家改名大师颜廷利:北京、上海、广州和深圳房价精准预测
在2024年国庆节期间,北京、上海、广州和深圳的房地产市场异常活跃。作为山东济南籍的国际易学权威颜廷利教授,连续收到了这些大城市客户的感谢信和电话。 来自北京的王先生在信中写道:“非常感谢颜廷利教授这几年来对我们的鼓励和支持。在经历…...
MySQL常用指令码
本文精心挑选了一系列MySQL指令码,助你提升资料库效率、解决常见问题,让你的资料储存体验更加高效、可靠。 常用功能指令码 1.汇出整个资料库 mysqldump - u 使用者名称- p – default - character - set latin1 资料库名>汇出的档名(资料库预设编…...

OpenHarmony(鸿蒙南向开发)——轻量系统内核(LiteOS-M)【扩展组件】
往期知识点记录: 鸿蒙(HarmonyOS)应用层开发(北向)知识点汇总 鸿蒙(OpenHarmony)南向开发保姆级知识点汇总~ 持续更新中…… C支持 基本概念 C作为目前使用最广泛的编程语言之一,…...
官方ROM 免费下载! 王者归来! 华为秘盒media Q M310(续)
最近在捣鼓电视盒子, 前帖讨论了如何拯救华为华为秘盒media Q M310, 详情请点击这里! https://blog.csdn.net/weixin_62598385/article/details/142658048 CSDN上有精简版的M310 ROM下载, 但是我点不进去, 要收年费&am…...
【Docker】05-Docker部署前端项目
1. nginx.conf worker_processes 1;events {worker_connections 1024; }http {include mime.types;default_type application/json;sendfile on;keepalive_timeout 65;server {listen 18080;# 指定前端项目所在的位置location / {root /usr/share/nginx…...

SQL进阶技巧:如何优化NULL值引发的数据倾斜问题?
目录 0 场景描述 1 问题分析 1.1 问题剖析 1.2 解决方案 2 小结 0 场景描述 实际业务中有些大量的null值或者一些无意义的数据参与到计算作业中,表中有大量的null值,如果表之间进行join操作,就会有shuffle产生,这样所有的null值都会被分配到一个reduce中,必然产生数…...

【09】纯血鸿蒙HarmonyOS NEXT星河版开发0基础学习笔记-Class类基础全解(属性、方法、继承复用、判断)
序言: 本文详细讲解了关于我们在程序设计中所用到的class类的各种参数及语法。 笔者也是跟着B站黑马的课程一步步学习,学习的过程中添加部分自己的想法整理为笔记分享出来,如有代码错误或笔误,欢迎指正。 B站黑马的课程链接&am…...

快速提升波段交易技能:4种实用策略分享
每个交易员的交易偏好是各不相同的,有人偏爱短线交易的迅速反应,有人钟情于中长线的稳健布局,还有人则热衷于波段交易的灵活操作。我们经常探讨短线与中长线的策略,但你了解波段交易的策略吗? 波段交易是什么…...

LeetCode 11 Container with Most Water 解题思路和python代码
题目: You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the co…...

【深度学习】损失函数
损失函数(Loss Function)是机器学习和深度学习模型中的一个核心概念,它用于衡量模型的预测输出与真实标签之间的差异。通过优化(最小化)损失函数,模型可以不断调整其内部参数,提升预测性能。不同…...
Python爬虫实战:研究MechanicalSoup库相关技术
一、MechanicalSoup 库概述 1.1 库简介 MechanicalSoup 是一个 Python 库,专为自动化交互网站而设计。它结合了 requests 的 HTTP 请求能力和 BeautifulSoup 的 HTML 解析能力,提供了直观的 API,让我们可以像人类用户一样浏览网页、填写表单和提交请求。 1.2 主要功能特点…...

突破不可导策略的训练难题:零阶优化与强化学习的深度嵌合
强化学习(Reinforcement Learning, RL)是工业领域智能控制的重要方法。它的基本原理是将最优控制问题建模为马尔可夫决策过程,然后使用强化学习的Actor-Critic机制(中文译作“知行互动”机制),逐步迭代求解…...
Spring Boot 实现流式响应(兼容 2.7.x)
在实际开发中,我们可能会遇到一些流式数据处理的场景,比如接收来自上游接口的 Server-Sent Events(SSE) 或 流式 JSON 内容,并将其原样中转给前端页面或客户端。这种情况下,传统的 RestTemplate 缓存机制会…...
连锁超市冷库节能解决方案:如何实现超市降本增效
在连锁超市冷库运营中,高能耗、设备损耗快、人工管理低效等问题长期困扰企业。御控冷库节能解决方案通过智能控制化霜、按需化霜、实时监控、故障诊断、自动预警、远程控制开关六大核心技术,实现年省电费15%-60%,且不改动原有装备、安装快捷、…...
Neo4j 集群管理:原理、技术与最佳实践深度解析
Neo4j 的集群技术是其企业级高可用性、可扩展性和容错能力的核心。通过深入分析官方文档,本文将系统阐述其集群管理的核心原理、关键技术、实用技巧和行业最佳实践。 Neo4j 的 Causal Clustering 架构提供了一个强大而灵活的基石,用于构建高可用、可扩展且一致的图数据库服务…...
拉力测试cuda pytorch 把 4070显卡拉满
import torch import timedef stress_test_gpu(matrix_size16384, duration300):"""对GPU进行压力测试,通过持续的矩阵乘法来最大化GPU利用率参数:matrix_size: 矩阵维度大小,增大可提高计算复杂度duration: 测试持续时间(秒&…...

OPENCV形态学基础之二腐蚀
一.腐蚀的原理 (图1) 数学表达式:dst(x,y) erode(src(x,y)) min(x,y)src(xx,yy) 腐蚀也是图像形态学的基本功能之一,腐蚀跟膨胀属于反向操作,膨胀是把图像图像变大,而腐蚀就是把图像变小。腐蚀后的图像变小变暗淡。 腐蚀…...
在web-view 加载的本地及远程HTML中调用uniapp的API及网页和vue页面是如何通讯的?
uni-app 中 Web-view 与 Vue 页面的通讯机制详解 一、Web-view 简介 Web-view 是 uni-app 提供的一个重要组件,用于在原生应用中加载 HTML 页面: 支持加载本地 HTML 文件支持加载远程 HTML 页面实现 Web 与原生的双向通讯可用于嵌入第三方网页或 H5 应…...
Java 二维码
Java 二维码 **技术:**谷歌 ZXing 实现 首先添加依赖 <!-- 二维码依赖 --><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.5.1</version></dependency><de…...

Reasoning over Uncertain Text by Generative Large Language Models
https://ojs.aaai.org/index.php/AAAI/article/view/34674/36829https://ojs.aaai.org/index.php/AAAI/article/view/34674/36829 1. 概述 文本中的不确定性在许多语境中传达,从日常对话到特定领域的文档(例如医学文档)(Heritage 2013;Landmark、Gulbrandsen 和 Svenevei…...