You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Gateway无法传递Token至资源服务,登录跳转异常求助

问题分析与解决方案

核心原因

你的game-config-service未配置为OAuth2资源服务器,导致它无法识别网关转发的Google Access Token,默认触发了Spring Security的登录重定向逻辑,将请求转到自身的/login端点。同时,网关的TokenRelay仅负责传递Token,但下游服务需要具备验证该Token的能力才能完成认证流程。


分步解决方案

1. 为game-config-service添加资源服务器依赖

如果使用Maven,在pom.xml中添加:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

2. 配置game-config-service的OAuth2资源服务器验证规则

在application.yml中添加以下配置,让服务能验证Google签发的JWT Token:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://accounts.google.com
          jwk-set-uri: ${spring.security.oauth2.resourceserver.jwt.issuer-uri}/.well-known/openid-configuration/jwks

3. 配置game-config-service的安全过滤链

创建安全配置类,指定服务为资源服务器,接受并验证JWT Token:

@Configuration
@EnableWebSecurity
public class ResourceServerConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(Customizer.withDefaults())
            );
        return http.build();
    }
}

4. 修改控制器获取用户信息的方式

原代码中的OAuth2Authentication是客户端侧的认证对象,资源服务器应使用OAuth2User来获取用户信息:

@Slf4j
@RestController
@RequestMapping(value = "api/v1/configuration/group")
public class GroupController {

    // ... 其他代码不变

    @GetMapping
    public List<GroupApi> getAll(@AuthenticationPrincipal OAuth2User oauth2User) {
        // 从Google返回的用户信息中提取字段
        String userName = oauth2User.getAttribute("name");
        String userEmail = oauth2User.getAttribute("email");
        log.info("当前登录用户:{},邮箱:{}", userName, userEmail);

        return groupService.getAll()
                .stream()
                .map(group -> mapper.map(group, GroupApi.class))
                .collect(Collectors.toList());
    }

    // ... 其他接口同理修改@AuthenticationPrincipal参数
}

5. 清理网关冗余配置

你的网关同时通过代码RouteLocator和yml配置了路由,会造成冲突,建议保留一种方式即可。例如删除WebSecurityConfig中的customRouteLocator Bean,仅保留yml中的路由配置(已包含TokenRelay默认过滤器)。

另外,yml中已经配置了Google客户端信息,无需再通过代码创建clientRegistrationRepository,可以删除该Bean以减少冗余。


验证流程

  1. 重启网关和game-config-service
  2. 访问http://localhost:9090/api/v1/configuration/group,完成Google认证后,会直接返回接口数据,不再重定向到8081/login
  3. 查看game-config-service的日志,能看到当前登录用户的姓名和邮箱信息

内容的提问来源于stack exchange,提问作者John Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 09:15:14