执行 CORS 请求时,nginx 反向代理设置不保留会话 ID

Posted

技术标签:

【中文标题】执行 CORS 请求时,nginx 反向代理设置不保留会话 ID【英文标题】:nginx reverse proxy setup does not preserve session id when doing CORS requests 【发布时间】:2013-05-22 22:17:39 【问题描述】:

这是我的设置: - 我在 nodejs 中实现了一个 http 服务器,它公开了 api 端点。这是通过 nginx 使用 ssl 反向代理到api.domain.com。这是配置:

 1 server                                                            
 2     listen 80;                                                      
 3     server_name api.domain.com;                                     
 4     access_log /var/log/nginx/api.access.log;                       
 5     location /                                                     
 6         proxy_pass    http://127.0.0.1:3000/;                       
 7                                                                    
 8                                                                    
 9                                                                     
 10 server                                                            
 11     listen 443;                                                    
 12     server_name api.domain.com;                                    
 13     access_log /var/log/nginx/api.access.log;                      
 14     ssl on;                                                        
 15     ssl_certificate /path/to/ssl/server.crt;     
 16     ssl_certificate_key /path/to/ssl/server.key;         
 17     location / 
 18         proxy_pass    https://127.0.0.1:3001/;                                
 19                                                                   
 20 

然后我让 nginx 在dashboard.domain.com 下提供一个静态上下文文件,该文件旨在使用来自api.domain.com 的api。这是设置:

  1 server                                                                                                                                  
  2     listen 80;                                                                  
  3     server_name dashboard.domain.com;                                        
  4     root /path/to/static/site;                                                                                             
  5   

我想使用 CORS 执行此操作,我确保静态站点上的 js 在所有请求中发送正确的 Origin 标头。我实现了一个非常简单的登录机制。这是我在 api 端点上使用的咖啡脚本代码:

# server.coffee
app.configure ->
    app.use middleware.setP3PHeader()
    app.use express.bodyParser()
    app.use express.cookieParser()
    app.use express.session
      secret: conf.session.secret
      key: conf.session.key
      cookie:
          maxAge: conf.session.maxAge
    app.use express.methodOverride()
    app.use express.query()
    app.use express.errorHandler()

# routes.coffee
app.options '*', shop.cors, shop.options
app.post '/login', shop.cors, shop.login
app.post '/logout', shop.cors, shop.logout
app.get '/current-user', shop.cors, shop.current

# shop.coffee
exports.options = (req, res) ->
    res.send 200

exports.cors = (req, res, next) ->
    allowed = ['http://dashboard.domain.com', 'http://localhost:3000']
    origin = req.get 'Origin'
    if origin? and origin in allowed
        res.set 'Access-Control-Allow-Origin', origin
        res.set 'Access-Control-Allow-Credentials', true
        res.set 'Access-Control-Allow-Methods', 'GET,POST'
        res.set 'Access-Control-Allow-Headers', 'X-Requested-With, Content-Type'
        next()
    else
        res.send 403, "Not allowed for #origin"

exports.login = (req, res) ->
    unless req.body.email? and req.body.password?
        res.send 400, "Request params not correct #req.body"
    models.Shop.findOne()
        .where('email').equals(req.body.email)
        .where('password').equals(req.body.password)
        .exec (err, shop) ->
            if err? then return res.send 500, err.message
            unless shop? then return res.send 401, "Not found for #req.body"

            req.session.shopId = shop.id
            res.send 200, shop.publish()

exports.logout = (req, res) ->
    delete req.session.shopId
    res.send 200

exports.current = (req, res) ->
    unless req.session.shopId?
        return res.send 401, "Not logged in!"
    models.Shop.findById(req.session.shopId)
        .exec (err, shop) ->
            if err? then return send.res 500, err.message
            unless shop? then return res.send 404, "No shop for #req.session.shopId"

            res.send 200, shop.publish()

问题是这样的: 1. 我首先打电话给/login,然后我与登录用户(req.session.shopId)建立了一个新会话 2. 然后我打电话给/current-user 但会话消失了! nodejs服务器接收到的session id不同,因此会创建不同的session

【问题讨论】:

【参考方案1】:

看起来您有一个全局代理指令 (proxy_pass),但您没有明确处理标头转发(其中,大概会话令牌作为 cookie 存在),并且您需要进一步考虑什么构成(共享)会话缓存键。

可能会尝试这样的事情:

location / 
   proxy_pass  http://127.0.0.1:3000/;                                
   proxy_redirect off;
   proxy_set_header   X-Real-IP  $remote_addr;
   proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
   proxy_set_header   X-Forwarded-Proto  $scheme;
   proxy_set_header   Host  $http_host;
   proxy_set_header   X-NginX-Proxy  true;
   proxy_http_version 1.1;
   proxy_cache pcache;
   proxy_cache_key   "$scheme$host$request_method$request_uri";

另外,如果 node.js 服务器在同一个盒子上,不知道你为什么要通过 localhost (proxy_pass https://127.0.0.1:3001/) 上的 ssl 连接。您可能需要考虑使用重写指令公开仅 SSL 的公众面孔,方法是:rewrite ^ https://api.domain.com$request_uri? permanent;

另请参阅:Node.js + Nginx - What now? [SO] 了解基本设置,http://www.ruby-forum.com/topic/4408747 了解有关 nginx 反向代理配置混乱中丢失(更糟糕 - 泄露!)会话的良好讨论。

【讨论】:

【参考方案2】:

如果你想拥有会话持久性,你需要确保你正确配置了express-session 模块。 resavesaveUninitialized 参数很重要。

来自文档:

重新保存

强制将会话保存回会话存储,即使 session 在请求期间从未被修改过。取决于您的商店 这可能是必要的,但它也可以创建竞争条件,其中 客户端向您的服务器发出两个并行请求,并对 当另一个请求时,一个请求中的会话可能会被覆盖 结束,即使它没有做任何改变(这种行为也取决于 您正在使用的商店)。

默认值为true,但不推荐使用默认值, 因为默认值将来会改变。请对此进行研究 设置并选择适合您的用例的内容。通常, 你会想要假的。

我如何知道我的商店是否需要这样做?最好的了解方式 是检查您的商店是否实现了触摸方法。如果它 确实如此,那么您可以安全地设置 resave: false。如果不执行 touch 方法和您的商店在存储时设置过期日期 会话,那么您可能需要重新保存:true。

保存未初始化

强制将“未初始化”的会话保存到存储中。一种 会话是新的但未修改时未初始化。选择 false 用于实现登录会话,减少服务器 存储使用,或遵守之前需要许可的法律 设置一个cookie。选择 false 也将有助于竞争条件 客户端在没有会话的情况下发出多个并行请求。

默认值为true,但不推荐使用默认值, 因为默认值将来会改变。请对此进行研究 设置并选择适合您的用例的内容。

请注意,如果您将 Session 与 PassportJS、Passport 结合使用 将在会话中添加一个空的 Passport 对象以供用户使用 已通过身份验证,这将被视为对 会话,导致它被保存。

我的一个应用程序有这个并且它正在工作:

app.use(session(
    store: new RedisStore(
        host: config.redis_instance_local_ip,
        port: config.redis_instance_local_port
    ),
    secret: config.application_session_secret,
    resave: false,
    saveUninitialized: true
));

另外,如果你想在多个节点上通过 nginx 负载均衡的粘性会话(或会话持久性),你应该有 nginx 的商业版本,nginx plus。见http://nginx.com/products/session-persistence/

【讨论】:

以上是关于执行 CORS 请求时,nginx 反向代理设置不保留会话 ID的主要内容,如果未能解决你的问题,请参考以下文章

CORS跨域与Nginx反向代理跨域优劣对比

CORS跨域与Nginx反向代理跨域优劣对比

Nginx转发+反向代理实现跨域接口转发

从此再也不担心Nginx跨域设置了

Nginx的反向代理跨域

nginx 反向代理时丢失端口的解决方案