【问题标题】:Ember send session id to Node on api callsEmber 在 API 调用上向 Node 发送会话 ID
【发布时间】:2017-04-06 17:40:44
【问题描述】:

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

我有 ember 与节点交谈(正确设置了 cors)。我能够登录用户并在服务器上创建会话,并将会话 ID 返回给 ember。然后,我使用服务器设置的相同 cookie 名称将会话 ID 存储在 cookie 中。我知道 ember 和 node 使用不同的端口,因此对方无法读取 cookie。我正在使用 ember-simple-auth 作为授权中间件。该部分目前一切正常。

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

//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 );
      }
        }
    });
        });

【问题讨论】:

  • 您能展示一下您用来尝试“注册”标头的代码/方法吗?
  • 我刚刚更新了问题以包含 ajax 调用和授权者的代码

标签: node.js ember.js ember-cli


【解决方案1】:

对于其他遇到同样问题的人来说,这是我为解决它所做的:

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

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

其中标头名称为“授权”,headerValue 为会话 ID

在你的 main 中的服务器端(节点)上面所有其他 app.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 替换为您的会话密码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 2021-09-03
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多