开发自定义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)是机器学习和深度学习模型中的一个核心概念,它用于衡量模型的预测输出与真实标签之间的差异。通过优化(最小化)损失函数,模型可以不断调整其内部参数,提升预测性能。不同…...

力扣 中等 46.全排列
文章目录 题目介绍题解 题目介绍 题解 代码如下: class Solution {List<List<Integer>> res new ArrayList<>();// 存放符合条件结果的集合List<Integer> path new ArrayList<>();// 用来存放符合条件结果boolean[] used; // 标记…...

LabVIEW机床加工监控系统
随着制造业的快速发展,机床加工的效率与稳定性成为企业核心竞争力的关键。传统的机床监控方式存在效率低、无法远程监控的问题。为了解决这些问题,开发了一种基于LabVIEW的机床加工监控系统,通过实时监控机床状态,改进生产流程&am…...

第五届智能设计国际会议(ICID 2024)
文章目录 一、会议详情二、重要信息三、大会介绍四、出席嘉宾五、征稿主题六、咨询 一、会议详情 二、重要信息 大会官网:https://ais.cn/u/vEbMBz提交检索:EI Compendex、IEEE Xplore、Scopus大会时间:2024年10月25-27日大会地点࿱…...

厨房用品分割系统源码&数据集分享
厨房用品分割系统源码&数据集分享 [yolov8-seg-C2f-DCNV3&yolov8-seg-AFPN-P345等50全套改进创新点发刊_一键训练教程_Web前端展示] 1.研究背景与意义 项目参考ILSVRC ImageNet Large Scale Visual Recognition Challenge 项目来源AAAI Global Al ln…...

【HTTPS】深入解析 https
我的主页:2的n次方_ 1. 背景介绍 在使用 http 协议的时候是不安全的,可能会出现运营商劫持等安全问题,运营商通过劫持 http 流量,篡改返回的网页内容,例如广告业务,可能会通过 Referer 字段 来统计是…...

Axios 快速入门
什么是Ajax Ajax 是一种通过 JavaScript 发送异步请求的技术,它的核心是使用 XMLHttpRequest 对象来与服务器交换数据。这种方式较为繁琐,因为需要手动处理请求状态和响应,并且编写的代码往往比较冗长。 相较之下,Axios 是一个基于…...

LabVIEW提高开发效率技巧----调度器设计模式
在LabVIEW开发中,针对多任务并行的需求,使用调度器设计模式(Scheduler Pattern)可以有效地管理多个任务,确保它们根据优先级或时间间隔合理执行。这种模式在需要多任务并发执行时特别有用,尤其是在实时系统…...

python之认识变量
1、变量 1.1、定义 字面意思来看,会发生改变的量称为变量。 相反的,如果有一个不会发生改变的量,它应该称为不变量,即常量。 1.2、引入变量的原因 主要是为了方便程序员动态的管理、操控数据。 1.3、变量的三要素 名称 类型…...

c++应用网络编程之十Linux下的Poll模式
一、Poll模式 在上一篇文章中提到了Select模式的缺点。既然有缺点,就要改正。但是直接在Select模式上修改不太现实,那么就推出一个新的模式不更香么?poll模式就应运而生了。不过,罗马不是一天建成的,poll模式也只是对…...

[C++][第三方库][RabbitMq]详细讲解
目录 1.介绍2.安装1.RabbitMq2.客户端库 3.AMQP-CPP 简单使用1.介绍2.使用 4.类与接口1.Channel2.ev 5.使用1.publish.cc2.consume.cc3.makefile 1.介绍 RabbitMQ:消息队列组件,实现两个客户端主机之间消息传输的功能(发布&订阅)核心概念࿱…...