首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Spring Cloud 搭建 Gateway 网关与统一登录模块:路径重写、登录拦截、跨域配置

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

作者头像
IT_陈寒
发布2025-06-01 13:19:16
发布2025-06-01 13:19:16
94900
代码可运行
举报
文章被收录于专栏:开发经验开发经验
运行总次数:0
代码可运行

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

一、项目结构

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

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

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

代码语言:javascript
代码运行次数:0
运行
复制
<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中配置路由和过滤器:

代码语言:javascript
代码运行次数:0
运行
复制
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

代码语言:javascript
代码运行次数:0
运行
复制
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中配置跨域:

代码语言:javascript
代码运行次数:0
运行
复制
spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: '*'
            allowedMethods:
              - GET
              - POST
              - PUT
              - DELETE
              - OPTIONS
            allowedHeaders:
              - '*'
            allowCredentials: true

三、统一登录模块

1. 配置 Spring Security

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

代码语言:javascript
代码运行次数:0
运行
复制
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          # 设置 JWT 解析器
          jwk-set-uri: http://auth-server/.well-known/jwks.json
2. 创建 Security 配置

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

代码语言:javascript
代码运行次数:0
运行
复制
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:

代码语言:javascript
代码运行次数:0
运行
复制
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。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-05-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、项目结构
    • 项目依赖
  • 二、搭建 Gateway 服务
    • 1. 配置 Gateway
    • 2. 配置跨域
  • 三、统一登录模块
    • 1. 配置 Spring Security
    • 2. 创建 Security 配置
    • 3. 实现认证过滤器
  • 四、总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档