我正在使用带有ember-simple-auth的ember-django-adapter,并为令牌认证编写了自定义授权器。我能够从服务器获取令牌,但无法使用适配器将其注入到api请求中。
应用程序/授权人/ application.js中
import Ember from 'ember';
import Base from 'ember-simple-auth/authorizers/base';
const { service } = Ember.inject;
export default Base.extend({
session: service('session'),
init: function () {
console.log('Intialize authorizer');
},
authorize(data, block) {
const accessToken = data['access_token'];
if (this.get('session.isAuthenticated') && !Ember.isEmpty(accessToken)) {
block('Authorization', `Token ${accessToken}`);
console.log("authorizer called with token: " + accessToken);
}
}
});
应用程序/适配器/ application.js中
import Ember from 'ember';
import DRFAdapter from 'ember-django-adapter/adapter/drf';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
const { service } = Ember.inject;
export default DRFAdapter.extend(DataAdapterMixin, {
session: service('session'),
authorizer: 'authorizer:application'
});
应用程序/认证器/ token.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
export default Base.extend({
serverTokenEndpoint: 'http://localhost:8000/ember-auth/',
authenticate: function(email, password) {
return new Ember.RSVP.Promise((resolve, reject) => {
Ember.$.ajax({
url: this.serverTokenEndpoint,
type: 'POST',
data: JSON.stringify({
email: email,
password: password
}),
contentType: 'application/json;charset=utf-8',
dataType: 'json'
}).then(function(response) {
console.log('Got token: ' + response.token);
Ember.run(function() {
resolve({
token: response.token
});
});
}, function(xhr) {
var response = xhr.responseText;
Ember.run(function() {
reject(response);
});
});
});
},
invalidate: function() {
console.log('invalidate...');
return Ember.RSVP.resolve();
}
});
Ember尝试转换到受保护的路由,但由于未注入Authorization标头,请求失败并显示403错误。
感谢任何帮助。