ember-cli simple-auth自定义授权

时间:2015-04-21 23:32:14

标签: ember.js ember-cli ember-simple-auth

我正在尝试将ember-simple-auth与自定义身份验证和授权一起使用:身份验证器可以正常运行,但授权者却没有。令牌已成功分配,但在ajax调用中没有注入。

应用程序/认证器/ custom.js

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

export default Base.extend({
    tokenEndpoint: 'http://...',

    restore: function(data) {
    return new Ember.RSVP.Promise(function(resolve, reject) {
      if (!Ember.isEmpty(data.token)) {
        resolve(data);
      } else {
        reject();
      }
    });
  },

  authenticate: function(credentials) {
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.$.ajax({
        url:         _this.tokenEndpoint,
        type:        'POST',
        data:        JSON.stringify({ username: credentials.identification, password: credentials.password }),
        contentType: 'application/json'
      }).then(function(response) {
        Ember.run(function() {
          resolve({ token: response.token });
        });
      }, function(xhr, status, error) {
        var response = JSON.parse(xhr.responseText);
        Ember.run(function() {
          reject(response.error);
        });
      });
    });
  },

  invalidate: function() {
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve) {
      Ember.$.ajax({ url: _this.tokenEndpoint, type: 'DELETE' }).always(function() {
        resolve();
      });
    });
  },
});

应用程序/授权人/ custom.js

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

export default Base.extend({
    authorize: function(jqXHR, requestOptions) {

        if (this.get('session.isAuthenticated') && !Ember.isEmpty(this.get('session.secure.token'))) {
            jqXHR.setRequestHeader('X-CSRFToken', this.get('session.secure.token'));
        }
    }
});

应用程序/初始化/ authentication.js

import CustomAuthenticator from 'app/authenticators/custom';
import CustomAuthorizer from 'app/authorizers/custom';

export default {
  name:       'authentication',
  before:     'simple-auth',
  initialize: function(container) {
    container.register('authenticator:custom', CustomAuthenticator);
    container.register('authorizer:custom', CustomAuthorizer);
  }
};

配置/ environment.js

  ENV['simple-auth'] = {
    authorizer: 'authorizer:custom',
    crossOriginWhitelist: ['http://...']
  };

应用程序/控制器/ login.js

import Ember from 'ember';

export default Ember.Controller.extend({
    actions: {
        authenticate: function(){
            var credentials = this.getProperties('identification', 'password');
            this.get('session').authenticate('authenticator:custom', credentials);

        }
    }
});

0 个答案:

没有答案