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

Spring Boot GraphQL项目中GraphiQL不发送Cookie导致403如何解决?

解决方案

首先问题根源是GraphiQL默认的fetch请求未开启credentials配置,导致浏览器不会自动携带当前域名下的Cookie发起请求,匹配Spring Security的身份校验规则失败返回403。你可以按以下步骤配置:

方案1:直接修改配置文件(适配Spring GraphQL 1.0+及新版本experimental starter)

直接在项目的application.yml(或application.properties)中添加如下配置即可,框架原生提供了控制该参数的配置项:

spring:
  graphql:
    graphiql:
      enabled: true
      # 配置GraphiQL发起请求时自动携带Cookie
      credentials: include

如果用properties格式,配置为:

spring.graphql.graphiql.enabled=true
spring.graphql.graphiql.credentials=include

方案2:适配旧版本experimental starter(无上述配置项的版本)

你需要自定义GraphiQL的初始化参数,修改fetch请求的配置,示例如下:

  1. 首先从starter提供的GraphiQL页面模板复制一份静态页面到resources/static/graphiql目录下
  2. 修改页面中GraphiQL初始化的fetcher配置,添加credentials: 'include'参数:
GraphiQL.createFetcher({
  url: '/graphql',
  fetchOptions: {
    credentials: 'include'
  }
})

补充Spring Security CORS配置注意项

如果你的GraphiQL访问域名和GraphQL接口域名不一致,需要同步调整Spring Security的跨域配置,允许携带凭证:

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.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.List;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .cors(cors -> cors.configurationSource(corsConfigurationSource()))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/graphiql/**", "/graphql").authenticated()
                .anyRequest().permitAll()
            );
        // 其他安全配置按原有逻辑保留即可
        return http.build();
    }

    private CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        // 此处替换为你实际允许的域名,不要使用*
        config.setAllowedOriginPatterns(List.of("http://*.example.com:8080", "http://*.blueorigin.com:8080"));
        config.setAllowedMethods(List.of("GET", "POST", "OPTIONS"));
        config.setAllowedHeaders(List.of("*"));
        // 允许跨域请求携带Cookie
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}

配置完成后重启应用,GraphiQL就会自动携带当前域名下的Cookie发起请求,不会再出现403错误。


内容的提问来源于stack exchange,提问作者Bob Kuhar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:48:04