2015-11-24 53 views
0

對不起(可能)愚蠢的問題。我對這個話題超級新!Ember-Simple-Auth:如何在ajax請求中注入令牌

我創建了一個自定義的授權:

import Ember from 'ember'; 
    import Base from 'ember-simple-auth/authorizers/base'; 
    export default Base.extend({ 
     authorize: function(jqXHR, requestOptions) { 
      var accessToken = this.get('session.content.secure.token'); 
      if (this.get('session.isAuthenticated') && !Ember.isEmpty(accessToken)) { 
       jqXHR.setRequestHeader('Authorization', 'Bearer ' + accessToken); 
      } 
     } 
    }); 

,現在我想在我的控制器中的Ajax請求的令牌(這是我的代碼,而無需令牌發送):

// app/controllers/workouts.js 
import Ember from 'ember'; 
import config from '../config/environment'; 

export default Ember.Controller.extend({ 
    requestEndpoint: config.ServerIp+'/workouts', 
    workouts: function() { 
     Ember.$.ajax({ 
      type: "GET", 
      url: requestEndpoint 
     }).success(function(data) { 
      return data; 
     }) 
    }.property() 
}); 

非常感謝您幫助和理解這個偉大的模塊!

回答

1

你可能有這樣的事情。

在您的授權:

// app/authorizers/your-authorizer.js 
import BaseAuthorizer from 'ember-simple-auth/authorizers/base'; 

export default BaseAuthorizer.extend({ 
    authorize(data, block) { 
     const accessToken = data.accessToken; //Data is the response returned by the server 
     if (!Ember.isEmpty(accessToken)) { 
      block('Authorization', `Bearer ${accessToken}`); 
     } 
    } 
}); 

適配器將添加授權頭到所有請求的護理:如果您使用的不是灰燼數據

// app/adapters/application.js 
import DS from 'ember-data'; 
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin'; 

export default DS.JSONAPIAdapter.extend(DataAdapterMixin, { 
    authorizer: 'authorizer:your-authorizer' 
}); 

,你可以去看看這個mixin的工作方式是創建自己的適配器:data-adapter-mixin

如果用戶沒有登錄,爲了保護您的路由免受訪問,您需要添加證書icated混入:

// app/routes/home.js 
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; 

export default Route.extend(AuthenticatedRouteMixin, { 
    ... 
}); 

而且不要忘記設置一些配置

// config/environment.js 
... 
var ENV = { 
    ... 
    'ember-simple-auth': { 
     authenticationRoute: 'login', 
     routeAfterAuthentication: 'home', 
     routeIfAlreadyAuthenticated: 'home' 
    } 
}