Ember 在 api 调用中将 session id 发送到节点

Ember send session id to Node on api calls

我有一个带有 ember 前端的 node/express 应用程序。我对这一切都不熟悉,所以请原谅这个(希望如此)简单的问题。

我 ember 与节点通信(正确设置了 cors)。我能够让用户登录并在服务器上创建一个 session,并且 return session ID 为 ember。然后,我使用服务器将设置的相同 cookie 名称将 session ID 存储在 cookie 中。我知道 ember 和节点使用不同的端口,所以对方无法读取cookie。我使用 ember-simple-auth 作为授权中间件。该部分目前一切正常。

我的问题是在随后的 api 调用中,服务器无法获取 session ID 来识别用户。我需要知道如何通过 ajax api 调用将 session ID 传回服务器。我尝试了一些尝试在 header 中传递它,但我做错了,因为它没有注册。通过 header 发送 session 的正确方法是什么?

//app/authorizers/custom.js

import Ember from 'ember';
import Base from 'ember-simple-auth/authorizers/base';

export default Base.extend({
   authorize(sessionData, block) {
    if (!Ember.isEmpty(sessionData.access_token)) {
      block('X-Authorization', 'Token: ' + this.get('sessionData.access_token'));
    }
  }
});

//app/controllers/application.js

this.get('session').authorize('authorizer:custom', (headerName, headerValue) => {
    $.ajax({
      dataType: "json",
      method: 'GET',
      url: ENV.APP.apiHost,
      data: {p: 'logout'},
      beforeSend: function(xhr){
        xhr.setRequestHeader(`${headerName}`, headerValue);
      },
      success: function( response ){
      if( response.success ){
        this.get('session').invalidate();
        this.transitionToLoginRoute();
      } else {
        console.log('something went wrong with server log out. json returned: ', response );
      }
        }
    });
        });

对于遇到同样问题的其他人,以下是我解决问题的方法:

1.) 在客户端(Ember) ajax调用,添加

beforeSend: function(xhr){
    xhr.setRequestHeader(`${headerName}`, headerValue);
},

其中 header 名称是 'Authorization',header值是 session ID

在您的主应用程序之上的服务器端(节点)。get/post/etc,添加

// CORS && client session id magic for API calls
app.all('/api/*', function( req, res, next ){
    corsIndex = $.inArray( req.headers.origin, config.CORS_WHITELIST );
    if( corsIndex > -1 ){
        res.header( 'Access-Control-Allow-Origin', config.CORS_WHITELIST[ corsIndex ]);
        res.header( 'Access-Control-Allow-Headers', 'Authorization');
    }

    // check for session id in authorize header. if true, set headers.cookie with signed session id
    var sid = req.headers.authorization;
    if(sid){
        var cookie = require('cookie'),
        signature = require('cookie-signature');
        var signed = 's:' + signature.sign(sid, config.SESS_SECRET);
        var data = cookie.serialize(config.SESS_COOKIE_NAME, signed);
        req.headers.cookie = data;
    }
    next();
});

如果您为 api 使用不同的路径,则需要更新“/api/*”。您还需要将 config.CORS_WHITELIST 换成一组白名单客户端,将 config.SESS_SECRET 换成您的 session 秘密。