开发自定义starter

news2024/10/7 11:38:20

环境: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-starter

security:
  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 {
    @Resource
    private SecurityConfig securityConfig;

    @Override
    public 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 框架提供的拦截器机制的一部分,但它们在使用场景和生命周期上有一定的区别:

  1. 应用范围:
  • WebRequestInterceptor 是一个更通用的拦截器接口,它可以应用于任何类型的请求(如 HTTP 请求)。
  • HandlerInterceptor 则专门用于 Web MVC 应用中的控制器方法调用前后。
  1. 生命周期:
  • 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 {
    @Resource
    private ServerProtectInterceptor serverProtectInterceptor;
    @Override
    public 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即可使用

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2194071.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

国外电商系统开发-运维系统文件上传

文件上传&#xff0c;是指您把您当前的PC电脑上的文件批量的上传到远程服务器上&#xff0c;在这里&#xff0c;您可以很轻松的通过拖动方式上传&#xff0c;只需要动动鼠标就搞定。 第一步&#xff0c;您应该选择要上传的服务器&#xff1a; 选择好了以后&#xff0c;点击【确…

SpringBoot框架下的教育系统开发全解析

1系统概述 1.1 研究背景 随着计算机技术的发展以及计算机网络的逐渐普及&#xff0c;互联网成为人们查找信息的重要场所&#xff0c;二十一世纪是信息的时代&#xff0c;所以信息的管理显得特别重要。因此&#xff0c;使用计算机来管理微服务在线教育系统的相关信息成为必然。开…

毕业设计项目——基于transformer的中文医疗领域命名实体识别(论文/代码)

完整的论文代码见文章末尾 以下为核心内容 摘要 近年来&#xff0c;随着深度学习技术的发展&#xff0c;基于Transformer和BERT的模型在自然语言处理领域取得了显著进展。在中文医疗领域&#xff0c;命名实体识别(Named Entity Recognition, NER)是一项重要任务&#xff0c;旨…

ArkUI中的状态管理

一、MVVM ArkUI提供了一系列装饰器实现ViewModel的能力,如@Prop、@Link、@Provide、LocalStorage等。当自定义组件内变量被装饰器装饰时变为状态变量,状态变量的改变会引起UI的渲染刷新。 在ArkUI的开发过程中,如果没有选择合适的装饰器或合理的控制状态更新范围,可能会导…

《大规模语言模型从理论到实践》第一轮学习笔记

第一章 绪论 本章主要介绍大规模语言模型基本概念、发展历程和构建流程。 大规模语言模型&#xff08;Large Language Models&#xff0c;LLM&#xff09;&#xff0c;也称大语言模型 或大型语言模型。 1.1 大规模语言模型基本概念 1.语言模型&#xff08;Language Model&a…

重学SpringBoot3-集成Redis(五)之布隆过滤器

更多SpringBoot3内容请关注我的专栏&#xff1a;《SpringBoot3》 期待您的点赞&#x1f44d;收藏⭐评论✍ 重学SpringBoot3-集成Redis&#xff08;五&#xff09;之布隆过滤器 1. 什么是布隆过滤器&#xff1f;基本概念适用场景 2. 使用 Redis 实现布隆过滤器项目依赖Redis 配置…

Spring开发最佳实践之跨域处理

1. 跨域处理 1.1 异常现象 1.2 异常原因分析 跨源资源共享的官方定义如下&#xff1a; 跨源资源共享&#xff08;CORS&#xff0c;Cross Origin Resource Sharing。或通俗地译为跨域资源共享&#xff09;是一种基于 HTTP 头的机制&#xff0c;该机制通过允许服务器标示除了它自…

上海理工大学《2023年+2019年867自动控制原理真题》 (完整版)

本文内容&#xff0c;全部选自自动化考研联盟的&#xff1a;《上海理工大学867自控考研资料》的真题篇。后续会持续更新更多学校&#xff0c;更多年份的真题&#xff0c;记得关注哦~ 目录 2023年真题 2019年真题 Part1&#xff1a;2023年2019年完整版真题 2023年真题 2019年…

Java使用线程池创建线程

一、线程前言 首先我们知道&#xff0c;线程的概念如果不知道可以去看这一篇Java中的线程&#xff0c;我们这篇主要讲述的是Java怎么使用线程池创建线程&#xff0c;首先我们要对线程池有点概念&#xff0c;其实顾名思义&#xff0c;线程池就是有喝多线程的一个池子类似于&…

一书讲透LLM大语言模型,《掌握大型语言模型》,看完我都懵了!

《掌握大型语言模型》 &#xff08;Mastering Large Language Models&#xff09;由Sanket Subhash Khandare撰写&#xff0c;是一本关于大型语言模型&#xff08;LLMs&#xff09;的高级技术、应用、前沿方法和顶尖模型的指南。 这本大模型书已经上传CSDN&#xff0c;朋友们如…

《Windows PE》4.2 绑定导入表

绑定导入表&#xff08;Bound Import Table&#xff09;是文件中的一个数据结构&#xff0c;用于存储已经绑定&#xff08;即完成绑定导入&#xff09;的外部函数的信息。 本节必须掌握的知识点&#xff1a; 绑定导入表数据结构 实例分析 4.2.1 绑定导入表数据结构 绑定导入…

【AIGC】ChatGPT是如何思考的:探索CoT思维链技术的奥秘

博客主页&#xff1a; [小ᶻZ࿆] 本文专栏: AIGC | ChatGPT 文章目录 &#x1f4af;前言&#x1f4af;什么是CoT思维链CoT思维链的背景与技术发展需求 &#x1f4af;CoT思维链的工作原理&#x1f4af;CoT思维链的应用领域&#x1f4af;CoT思维链的优势&#x1f4af;CoT思维…

动态内存管理笔试题

目录 1.第一题1.1如何修改 2.第二题2.1题想2.2深刻理解 3.第三题4.第四题 1.第一题 void GetMemory(char* p) {p (char*)malloc(100); } void Test(void) {char* str NULL;GetMemory(str);strcpy(str, "hello world");printf(str); }请问运⾏Test 函数会有什么样的…

解锁数字化营销成功密码

在趋势部分&#xff0c;列举了移动优先、社交媒体主导、个性化营销、视频营销崛起和数据驱动决策等方面&#xff0c;让读者快速了解数字化营销的发展方向。策略部分强调了明确目标受众、制定整合营销策略、优化用户体验、重视内容营销和社交媒体营销以及利用搜索引擎优化和数据…

jQuery——平滑翻页

平滑翻页 param next true&#xff1a;下一页 false&#xff1a;下一页 本文分享到此结束&#xff0c;欢迎大家评论区相互讨论学习&#xff0c;下一篇继续分享jQuery中循环翻页的学习。

Docker 实践与应用举例

Docker 实践与应用举例 Docker 已经成为现代软件开发和部署中的重要工具&#xff0c;通过容器化技术&#xff0c;开发者可以轻松管理应用的依赖环境、简化部署流程&#xff0c;并实现跨平台兼容性。本篇博客将详细介绍 Docker 的基本概念、实践操作以及应用场景&#xff0c;帮…

工业缺陷检测深度学习方法

工业缺陷检测深度学习方法 基于深度学习的工业缺陷检测方法可以降低传统人工质检的成本, 提升检测的准确性与效率, 因而在智能制造中扮演重要角色, 并逐渐成为计算机视觉领域新兴的研究热点之一. 其被广泛地应用 于无人质检、智能巡检、质量控制等各种生产与运维场景中. 本综述…

跨设备剪贴板同步服务ClipCascade

什么是 ClipCascade &#xff1f; ClipCascade 是一款开源的轻量级工具&#xff0c;可以自动同步您的剪贴板在多个设备之间&#xff0c;无需按键。它确保设备之间无缝的剪贴板共享&#xff0c;并以端对端加密优先保护隐私。无论您是在不同工作站之间切换&#xff0c;还是仅仅希…

检索增强思考 RAT(RAG+COT):提升 AI 推理能力的强大组合

在人工智能领域&#xff0c;大型语言模型&#xff08;LLMs&#xff09;已经取得了显著的进展&#xff0c;能够生成类似人类的文本并回答各种问题。然而&#xff0c;它们在推理过程中仍面临一些挑战&#xff0c;例如缺乏对事实的准确把握以及难以处理复杂的多步骤问题。为了解决…

Unity3D 单例模式

Unity3D 泛型单例 单例模式 单例模式是一种创建型设计模式&#xff0c;能够保证一个类只有一个实例&#xff0c;提供访问实例的全局节点。 通常会把一些管理类设置成单例&#xff0c;例如 GameManager、UIManager 等&#xff0c;可以很方便地使用这些管理类单例&#xff0c;…