NGINX 反向代理 WebSockets,并进行 JWT 认证,但没有 Access-Control-Allow-Origin 头部
我的目标是使用 NGINX 反向代理服务器来终止前端的 wss 连接并建立与后端的 ws 连接。我还需要使用 JWT 令牌对客户端进行身份验证,我成功地发出令牌并通过 Cookie 传递给了 NGINX 代理。
我使用 nginx-jwt 包 (https://github.com/auth0/nginx-jwt) 与 NGINX 的 OpenResty 分发。我的 nginx.conf 文件如下:
env JWT_SECRET; env JWT_SECRET_IS_BASE64_ENCODED; http { ... lua_package_path "usr/local/openresty/nginx-jwt;;"; map $http_upgrade $connection_upgrade { default upgrade; '' close; } upstream appserver { server [server ip]:[port]; } server { server_name api.[domain].org; listen 443 ssl; listen 80; ssl on; ssl_certificate /etc/letsencrypt/live/api.[domain].org/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/dev.[domain].org/privkey.pem; locaiton /connect { access_by_lua_block { local jwt = require("nginx-jwt") jwt.auth() } proxy_pass http://appserver$uri; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; add_header Access-Control-Allow-Origin https://[domain].org; } } }
当我尝试从浏览器访问 [domain].org/connect/[sockjs stuff] 时,我会得到以下错误:
Failed to load https://api.[domain].org/connect/info?t=1531334401388: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://[domain].org' is therefore not allowed access. The response had HTTP status code 500.
奇怪的是,当我注释掉 access_by_lua_block{} 时,我得到一个 200 的响应,但是有以下错误:
Failed to load https://api.[domain].org/connect/info?t=1531336691243: The 'Access-Control-Allow-Origin' header contains multiple values 'https://[domain].org, https://[same domain].org', but only one is allowed. Origin 'https://[domain].org' is therefore not allowed access.
并且没有建立任何 WebSocket 连接。
但是,如果我同时注释掉 access_by_lua_block{} 和 add_header Access-Control-Allow-Origin https://[domain].org; ,我就能成功地与后端建立 WebSocket 连接。
我已经连续几天一直在解决这个问题。请帮帮我。
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?

问题已解决:我的
lua_package_path上的相对路径指向的是一个目录而不是实际的*.lua文件。我将路径更改为/usr/local/openresty/nginx-jwt/?.lua;/usr/local/openresty/nginx-jwt/lib/?.lua;;。我还从
nginx.conf中删除了add_header Access-Control-Allow-Origin,因为我也在后端处理它,所以会因为Access-Control-Allow-Origin标头的多个条目而出现错误。显然,浏览器抛出的 CORS 错误只是由于浏览器由于代码中的错误而无法访问有效的端点所导致的结果。