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

Spring Security下GraphiQL无法访问/graphql的解决方案咨询

解决Spring Security限制GraphiQL访问/graphql端点的问题

针对Spring Boot 3.1.4 + Spring For GraphQL 1.2.3的场景,要保留/graphql的安全性同时让GraphiQL正常使用,需要调整Spring Security配置,核心是放行GraphiQL的静态资源并允许GraphiQL发起的认证请求访问/graphql,具体步骤如下:

1. 修正静态资源放行路径

你之前尝试放行/vendor/**是错误的,Spring For GraphQL内置的GraphiQL静态资源路径是/graphiql/**,需要把这个路径加入白名单。

2. 配置Spring Security过滤器链

创建或修改Spring Security配置类,确保GraphiQL能正常加载,同时/graphql端点仍需认证:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // 若使用Cookie认证需配置CSRF令牌传递,否则可关闭
            .csrf(csrf -> csrf.disable())
            // 配置请求授权规则
            .authorizeHttpRequests(auth -> auth
                // 放行GraphiQL的UI页面和静态资源
                .requestMatchers("/graphiql", "/graphiql/**").permitAll()
                // 允许/graphql的预检OPTIONS请求(浏览器跨域预检用)
                .requestMatchers(HttpMethod.OPTIONS, "/graphql").permitAll()
                // 其他所有请求(包括/graphql的POST查询)必须认证
                .anyRequest().authenticated()
            )
            // 根据实际认证方式配置,示例为表单登录,可替换为JWT、OAuth2等
            .formLogin(form -> form.permitAll());

        return http.build();
    }
}

3. 配置GraphiQL携带认证信息

确保GraphiQL发起请求时携带认证凭证:

  • Basic认证:在GraphiQL UI的Headers栏添加{"Authorization": "Basic 你的Base64编码账号密码"}
  • JWT认证:添加{"Authorization": "Bearer 你的Token"}
  • Session认证:登录后浏览器会自动携带Cookie,同域下默认支持,无需额外配置

4. 验证配置

启动应用后:

  1. 访问/graphiql,能正常加载UI界面
  2. 在GraphiQL中发送查询请求,携带认证头后可正常获取数据
  3. 直接用Postman等工具访问/graphql,未携带认证信息时会返回401,确保端点安全性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 09:40:05