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

Unity WebGL嵌入iframe连Spring Boot WebSocket遇403问题求助

解决方案建议

1. 放行WebSocket端点的访问权限

Spring Security默认会拦截所有请求,包括WebSocket的握手请求。你需要在SecurityConfig里明确放行WebSocket的端点路径(替换成你实际使用的WebSocket路径,比如/ws/**):

@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests()
            .requestMatchers(new AntPathRequestMatcher("/images/**"))
            .permitAll()
            .requestMatchers(new AntPathRequestMatcher("/ws/**")) // 替换为你的WebSocket实际路径
            .permitAll();
    http.headers().frameOptions().sameOrigin();
    super.configure(http);
    setLoginView(http, LoginView.class, LOGOUT_URL);
}

2. 配置WebSocket相关的CORS规则

线上环境的跨域限制更严格,即使iframe同域名,WebSocket握手也可能触发CORS校验。添加CORS配置类允许WebSocket请求:

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 线上建议指定具体域名,不要用*
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        // 显式允许WebSocket握手常用的GET/POST方法
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        source.registerCorsConfiguration("/ws/**", config); // 对应WebSocket端点路径
        return new CorsFilter(source);
    }
}

3. 避免Vaadin安全规则覆盖配置

VaadinWebSecurity有自己的请求拦截逻辑,确保WebSocket的放行配置在调用super.configure(http)之前执行,避免被Vaadin的默认规则覆盖。

4. 完善Nginx的WebSocket转发配置

虽然你已验证Nginx转发正常,但需确保WebSocket相关的头信息被正确传递:

location /ws {
    proxy_pass http://localhost:8080/ws;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

5. 检查Unity WebGL的连接协议

线上环境必须使用WSS协议(对应HTTPS),确保Unity中WebSocket的连接地址是wss://你的域名/websocket路径,避免浏览器拦截混合内容。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:25:20