Ember-simple-auth 防止会话在 401 响应时失效

Ember-simple-auth prevent session invalidation on 401 reponse

我正在使用 Ember:2.11.0,ember-简单验证:1.2.0

我使用 ember-simple-auth 通过 oauth2 向我的 REST API.

验证我的应用程序

ember-simple-auth 的标准行为是在服务器响应 401 状态代码时使用户会话无效。 我想以不同的方式处理并尝试覆盖它:

import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

export default DS.RESTAdapter.extend(DataAdapterMixin, {
  host: 'http://localhost:3000',
  authorizer: 'authorizer:oauth2',

  /*
  * The DataAdapterMixin invalidetes the session automatically if the server
  * returns the status 401. We don't want this behaviour, so we override
  * the handleResponse method.
  */
  handleResponse(status) {
    console.log(status);
    return this._super(...arguments);
  }

});

在我的 RestAdapter 中,我使用 DataAdapterMixin 触发 handleResponse 方法中的失效。 所以我试图在我的适配器中重写这个方法。我的方法被调用了,但是在我的方法完成后,mixins 方法被 ember 调用,正如你在这里看到的:

Ember superWrapper 方法的注释指出,它是用来处理对超级 class 方法的调用并将它们重定向到它,但不知何故它似乎将它重定向到混合。

我不知道为什么会这样。这可能可以通过直接编辑 DataAdapterMixin 来解决,但认为就与 ember-simple-auth

的未来版本的兼容性而言,这不是一个好主意

如果有人能指出正确的方向使覆盖工作,我将不胜感激。

当你从 mixin 扩展适配器时,this._super(...arguments); 将调用 mixin 的方法(如果它有这样的方法)。这就是为什么您的覆盖不起作用。您有以下选项:

  1. 查看 ember-data 源代码并从 DS.RESTAdapter (start from here) 复制 handleResponse 代码。没有 this._super 调用 - 没有 mixin 的影响。这可能不像听起来那么容易,并且可能与 ember data
  2. 的未来版本不兼容
  3. 通过从 ember-simple-auth 和 removing/modifying 复制代码创建您自己的 DataAdapterMixin 这是 handleResponse 方法。这可能与 ember-simpe-auth.
  4. 的未来版本不兼容
  5. 在调用this._super(...arguments)之前修改arguments,因此状态将是400而不是401:

    handleResponse: function (status) {
      /**
       * Modify status
       */
      if (status === 401) {
        status = 400;
      }
    
      /**
       * Replace status in arguments.
       */
      var args = Array.prototype.slice.call(arguments, 0);
      args.splice(0, 1, status);
    
      /**
       * Call parent's method
       */
      return this._super(...args);
    }
    

    此方法与未来版本兼容 - 即使将添加新参数(目前参数为 statusheaderspayload),此代码仍可使用。如果状态不再是第一个参数,它将停止工作(我认为这不会在不久的将来发生)。

但我还想说您的后端可能有问题:401 表示 "unathorized" 并且 ember-simple-auth 做了在这种情况下应该做的事情 - 使会话无效。如果你在某些情况下需要特殊身份,我建议使用418(我是茶壶)。