【问题标题】:Emberjs: How to invalidate session in custom authentication initializerEmberjs:如何在自定义身份验证初始化程序中使会话无效
【发布时间】:2016-05-30 06:47:28
【问题描述】:

我正在使用带有 cookie 身份验证的 ember-simple-auth 1.1.0,并创建了一个具有功能(恢复、身份验证和无效)的自定义身份验证器和自定义身份验证器的初始化程序。

我绑定了 ajaxError 事件,以便我们可以捕获任何错误。例如访问带有服务器响应 401 Not Authorized 的路由。我想使会话无效并将用户重定向回登录页面。

目前我无法在初始化程序中获取 ember-simple-auth 默认会话,因此我可以使会话无效。我没有为我的应用程序创建任何自定义会话。

最好的方法是什么?

如果不可能,最好在初始化程序上触发事件并在路由中捕获该事件?我们如何做到这一点?

我的自定义初始化程序如下所示:

import BasicAuthenticator from '../authenticators/basic';

export default {
  before: 'ember-simple-auth',
  name: 'basic-authenticator',
  initialize(application) {
    application.register('authenticator:basic', BasicAuthenticator);
    Ember.$(document).ajaxError((event, jqxhr, settings, reason) => {
      if (jqxhr.status === 401) {

      }
    });
  }
};

我的自定义身份验证器:

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

export default Base.extend({
  restore() {
    return new Ember.RSVP.Promise(function(resolve, reject) {
      let sessionCookie = window.Cookies.get('beaker.session.id');
      if(!window.isUndefined(sessionCookie)) {
        resolve(true);
      }else{
        reject();
      }
    });
  },
  authenticate(data) {
    return new Ember.RSVP.Promise(function (resolve, reject) {
      Ember.$.ajax({
        type: 'post',
        url: '/core/authentication/basic/login',
        data: data
    }).then((response) => {
        resolve({
          responseText: response
        });
      }, (error) => {
        reject(error);
      });
    });
  },
  invalidate() {
    return new Ember.RSVP.Promise(function (resolve, reject) {
      Ember.$.ajax({
        type: 'post',
        url: '/core/authentication/basic/logout'
      }).then(() => {
         resolve(true);
       }, () => {
         reject();
      });
    });
  }
});

【问题讨论】:

    标签: ember.js ember-simple-auth


    【解决方案1】:

    我找到了如何在初始化程序中获取会话的解决方案。

    在我找到的解决方案下面:

    import BasicAuthenticator from '../authenticators/basic';
    
    export default {
      before: 'ember-simple-auth',
      name: 'basic-authenticator',
      initialize(application) {
        application.register('authenticator:basic', BasicAuthenticator);
        Ember.$(document).ajaxError((event, jqxhr, settings, reason) => {
          let service = application.__container__.lookup('service:session');
          let session = service.get('session');
          if (jqxhr.status === 401) {
           session.invalidate();
          }
        });
      }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-31
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多