当前位置: 首页 > article >正文

Spring Cloud 搭建 Gateway 网关与统一登录模块:路径重写、登录拦截、跨域配置

文章目录

    • 一、项目结构
      • 项目依赖
    • 二、搭建 Gateway 服务
      • 1. 配置 Gateway
      • 2. 配置跨域
    • 三、统一登录模块
      • 1. 配置 Spring Security
      • 2. 创建 Security 配置
      • 3. 实现认证过滤器
    • 四、总结

博主介绍:全网粉丝10w+、CSDN合伙人、华为云特邀云享专家,阿里云专家博主、星级博主,51cto明日之星,热爱技术和分享、专注于Java技术领域
🍅文末获取源码联系🍅
👇🏻 精彩专栏推荐订阅👇🏻 不然下次找不到哟

在微服务架构中,Spring Cloud Gateway 是一种流行的API网关解决方案,它可以处理路由、负载均衡、安全、监控等任务。通过Spring Cloud Gateway,我们可以实现路径重写、登录拦截以及跨域配置等功能。本文将介绍如何搭建一个Spring Cloud Gateway网关,并实现上述功能。

在这里插入图片描述

一、项目结构

在搭建Spring Cloud Gateway网关之前,确保你的项目结构如下:

  1. Gateway 服务:作为网关服务,负责路由、过滤、跨域等配置。
  2. 统一登录模块:处理用户认证和授权。

项目依赖

首先,确保你的pom.xml中包含以下依赖:

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Spring Cloud Gateway -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <!-- Spring Cloud Starter Security (用于统一登录模块) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <!-- Spring Boot Starter OAuth2 Resource Server (用于JWT解析) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>
    <!-- 其他依赖 -->
</dependencies>

确保你已经在pom.xml中添加了Spring Cloud BOM管理和Spring Boot版本的相关配置。

二、搭建 Gateway 服务

1. 配置 Gateway

application.yml中配置路由和过滤器:

spring:
  cloud:
    gateway:
      routes:
        - id: serviceA
          uri: http://localhost:8081
          predicates:
            - Path=/serviceA/**
          filters:
            - StripPrefix=1
            - RewritePath=/serviceA/(?<segment>.*), /${segment}
        - id: serviceB
          uri: http://localhost:8082
          predicates:
            - Path=/serviceB/**
          filters:
            - StripPrefix=1
            - RewritePath=/serviceB/(?<segment>.*), /${segment}
      default-filters:
        - AddRequestHeader=Default-Header, DefaultValue
  • 路由配置/serviceA/**/serviceB/** 路由到相应的服务。
  • 路径重写StripPrefix 去掉前缀,RewritePath 重写路径。
  • 默认过滤器:添加一个默认的请求头。

2. 配置跨域

Gateway中配置跨域,使用Spring Cloud Gateway的GlobalCorsProperties

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

application.yml中配置跨域:

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: '*'
            allowedMethods:
              - GET
              - POST
              - PUT
              - DELETE
              - OPTIONS
            allowedHeaders:
              - '*'
            allowCredentials: true

三、统一登录模块

1. 配置 Spring Security

application.yml中配置安全策略和认证服务器:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          # 设置 JWT 解析器
          jwk-set-uri: http://auth-server/.well-known/jwks.json

2. 创建 Security 配置

在 Spring Boot 应用中创建一个配置类:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/login", "/public/**").permitAll()
                .anyRequest().authenticated()
            .and()
            .oauth2ResourceServer()
                .jwt();
    }
    
    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/swagger-ui.html", "/v2/api-docs");
    }
}

3. 实现认证过滤器

创建一个认证过滤器,用于拦截请求和验证token:

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 从请求中提取 JWT token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            // 解析并验证 token
            // 如果验证成功,设置 SecurityContext
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        chain.doFilter(request, response);
    }
}

四、总结

通过以上步骤,我们成功地使用Spring Cloud Gateway搭建了一个网关服务,并实现了以下功能:

  1. 路径重写:在网关层处理路径重写,将请求转发到对应的服务。
  2. 登录拦截:通过Spring Security配置统一的登录认证机制,并通过JWT验证用户身份。
  3. 跨域配置:在网关中配置跨域设置,确保前端和后端服务能够顺利交互。

这种配置方式可以有效地将认证、授权、跨域处理等问题集中在网关层,实现统一管理,简化各微服务的开发与维护。希望这篇文章能帮助你在实际项目中顺利搭建和配置Spring Cloud Gateway。如果你有任何问题或建议,欢迎在评论区留言交流!

大家点赞、收藏、关注、评论啦 、查看👇🏻获取联系方式👇🏻


http://www.kler.cn/news/303372.html

相关文章:

  • 使用Jenkins扩展钉钉消息通知
  • 根据NVeloDocx Word模板引擎生成Word(五)
  • 9.12 TFTP通信
  • 阿里巴巴拍立淘API:实时图像搜索与快速响应的技术探索
  • Pycharm Remote Development 报错解决
  • 【机器学习(三)】分类和回归任务-随机森林-Sentosa_DSML社区版
  • 【数据库】死锁排查方式
  • iPhone 16分辨率,屏幕尺寸,PPI 详细数据对比 iPhone 16 Plus、iPhone 16 Pro、iPhone 16 Pro Max
  • CTF比赛中的Git相关题目解题思路
  • Unity 之 【Android Unity FBO渲染】之 [Unity 渲染 Android 端播放的视频] 的一种方法简单整理
  • TESSY创建需要手写桩的测试用例
  • 麒麟桌面操作系统:查看最近安装与卸载的软件包
  • Unreal Fest 2024 虚幻引擎影视动画制作的普遍问题
  • 基于云计算的虚拟电厂负荷预测
  • Vue3前端框架学习记录
  • 《深度学习》—— 神经网络基本结构
  • Java 之 Lambda表达式
  • 刚接触无处下手?水下航行器AUV/UUV六自由度模型/控制器设计matlab/simulink参考代码,基础的/进阶的,入门到顺利毕业/完成课题/发表论文。
  • Java微服务架构最佳实践:如何设计高可用的分布式系统
  • 华为 HCIP 认证费用和报名资格
  • Java 开发中锁的选择与使用
  • MVC设计模式与delegate,tablview,Appdelegate,SceneDelegate
  • 【逐行注释】自适应观测协方差R的AUKF(自适应无迹卡尔曼滤波,MATLAB语言编写),附下载链接
  • 小程序给对象赋值(双向绑定)方法之一
  • 企业客户|基于springboot的企业客户管理系统设计与实现(附项目源码+论文+数据库)
  • 一次开发,多端部署--实例二
  • RK3568 android11 usb摄像头预览分辨率添加多分辨率---解除1080p限制
  • 实现绑定UDP端口的Server程序
  • 大模型微调 - 基于预训练大语言模型的对话生成任务 训练代码
  • 计算机二级自学笔记(选择题1部分)