Ember-Simple-Auth:如何在ajax请求中注入令牌

时间:2015-11-24 11:56:58

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

抱歉(也许)这个愚蠢的问题。我是这个话题的新手!

我创建了一个自定义授权程序:

    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 个答案:

答案 0 :(得分: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'
});

如果你没有使用ember数据,你可以看看这个mixin如何工作来创建你自己的适配器:data-adapter-mixin

如果用户未被记录,为了保护您的路由不被访问,您需要添加经过身份验证的mixin:

// 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'
    }
}