具有JWT身份验证的NGINX反向代理WebSocket否Access-Control-Allow-Origin标头

时间:2018-07-11 19:04:03

标签: websocket lua jwt nginx-reverse-proxy openresty

我的目标是使用NGINX代理服务器终止来自前端的wss连接并建立与我的后端的ws连接。我还需要使用JWT令牌对客户端进行身份验证,我已成功发行该令牌并将其通过Cookie传递给NGINX代理。

我正在使用nginx-jwt发行版的OpenResty软件包(https://github.com/auth0/nginx-jwt)。我的NGINX文件如下所示:

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.时,我得到200响应,但有错误:

access_by_lua_block{}

并且没有建立Websocket连接。

但是如果我同时注释掉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.access_by_lua_block{},我就能成功建立到后端的Websocket连接。

这几天来,我的头一直在撞墙。请帮忙。

1 个答案:

答案 0 :(得分:0)

已解决:我的lua_package_path上的相对路径指向目录,而不是实际的*.lua文件。我将路径更改为/usr/local/openresty/nginx-jwt/?.lua;/usr/local/openresty/nginx-jwt/lib/?.lua;;

我还从add_header Access-Control-Allow-Origin中删除了nginx.conf,因为我也在后端处理了这个问题,所以我在Access-Control-Allow-Origin标头的多个条目上遇到了错误。

显然,由于代码中的错误,浏览器引发的CORS错误仅仅是浏览器无法命中有效端点的结果。