网站建设对旅游意义,wordpress卸载插件,免费的网站模板下载,图库网站源码下载环境#xff1a;Spring Cloud Gateway
需求#xff1a;防止用户绕过网关直接访问服务器#xff0c;用户只需引入依赖即可。
1、创建项目
首先创建一个spring boot项目 2、配置pom.xml
?xml version1.0 encodingUTF-8?
project xm…环境Spring Cloud Gateway
需求防止用户绕过网关直接访问服务器用户只需引入依赖即可。
1、创建项目
首先创建一个spring boot项目 2、配置pom.xml
?xml version1.0 encodingUTF-8?
project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.7.15/versionrelativePath/ !-- lookup parent from repository --/parentgroupIdio.github.lanxiu-code/groupIdartifactIdsecurity-spring-boot-starter/artifactIdversion1.0.0/versionnamesecurity-spring-boot-starter/namedescriptionsecurity-spring-boot-starter/descriptionurlhttps://github.com/lanxiu-code/security-spring-boot-starter/urllicenseslicensenameThe Apache Software License, Version 2.0/nameurlhttp://www.apache.org/licenses/LICENSE-2.0.txt/url/license/licensesdevelopersdeveloperidlanxiu/idnamelanxiu/nameemail3403138527qq.com/emailrolesroleProject Manager/roleroleArchitect/role/roles/developer/developersscmconnectionhttps://github.com/lanxiu-code/security-spring-boot-starter.git/connectiondeveloperConnectionscm:git:ssh://gitgithub.com:lanxiu-code/security-spring-boot-starter.git/developerConnectionurlhttps://github.com/lanxiu-code/security-spring-boot-starter/url/scmpropertiesjava.version1.8/java.versionproject.build.sourceEncodingUTF-8/project.build.sourceEncoding/propertiesdependenciesdependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdoptionaltrue/optional/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency!-- 提供了自动装配功能--dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-autoconfigure/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-configuration-processor/artifactIdoptionaltrue/optional/dependency/dependenciesbuildpluginsplugingroupIdorg.apache.maven.plugins/groupIdartifactIdmaven-compiler-plugin/artifactIdconfigurationsource${java.version}/sourcetarget${java.version}/target/configuration/pluginplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactIdconfigurationskiptrue/skip/configuration/plugin!-- central发布插件 --plugingroupIdorg.sonatype.central/groupIdartifactIdcentral-publishing-maven-plugin/artifactIdversion0.4.0/versionextensionstrue/extensionsconfigurationpublishingServerIdlanxiu/publishingServerIdtokenAuthtrue/tokenAuth/configuration/plugin!-- source源码插件 --plugingroupIdorg.apache.maven.plugins/groupIdartifactIdmaven-source-plugin/artifactIdexecutionsexecutionidattach-sources/idgoalsgoaljar-no-fork/goal/goals/execution/executions/plugin!-- javadoc插件 --plugingroupIdorg.apache.maven.plugins/groupIdartifactIdmaven-javadoc-plugin/artifactIdversion2.9.1/versionexecutionsexecutionidattach-javadocs/idgoalsgoaljar/goal/goals/execution/executions/pluginplugingroupIdorg.apache.maven.plugins/groupIdartifactIdmaven-gpg-plugin/artifactIdversion1.6/versionconfigurationexecutableD:\software\GPG\GnuPG\bin\gpg.exe/executablekeynamelanxiu-code/keyname/configurationexecutionsexecutionidsign-artifacts/idphaseverify/phasegoalsgoalsign/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.EnableAutoConfigurationcom.lx.security.SecurityAutoConfiguration如果是SpringBoot3版本要在
METE-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports中配置自动配置
com.lx.security.SecurityAutoConfiguration9、打包 maven install 10、引入项目
!-- 安全认证依赖 --
dependencygroupIdcom.lx.security/groupIdartifactIdsecurity-spring-boot-starter/artifactIdversion1.0.0/version
/dependency引入项目后配置好yml即可使用