【发布时间】:2015-11-05 04:57:28
【问题描述】:
我正在尝试设置一个简单的 Ember.js 应用程序来与自定义 API 服务器通信,并使用 JWT 身份验证。 我可以在 API 服务器上登录并获取 JWT 令牌,但随后对 API 服务器的调用中没有设置授权标头。
我的登录控制器是:
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
authenticate: function() {
var credentials = this.getProperties('identification', 'password'),
authenticator = 'simple-auth-authenticator:jwt';
this.get('session').authenticate(authenticator, credentials).then(function() {
// authentication was successful
console.log('OK');
}, function(err) {
// authentication failed
console.log('FAIL ' + JSON.stringify(err));
});
},
logOut: function() {
this.get('session').invalidate();
}
}
});
我可以成功登录并获得令牌。我的登录路径:
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
sessionAuthenticationFailed: function(error) {
console.log('Login error: ' + error.ErrorDesc);
this.controllerFor('login').set('loginErrorMessage', error.ErrorDesc);
this.controllerFor('login').set('ErrorMoreInfo', error.MoreInfo);
},
sessionAuthenticationSucceeded: function() {
console.log('Session authenticated: ' + this.get('session').content.secure.token);
// redirect to last route requested, or to default route
var attemptedTransition = this.get('session').get('attemptedTransition');
if (attemptedTransition) {
attemptedTransition.retry();
this.get('session').set('attemptedTransition', null);
} else {
this.transitionTo('index');
}
}
}
});
...向我显示令牌已正确获取,并将我正确重定向到我的受保护路线(例如索引)。从那时起,如果我尝试从 API 服务器获取任何数据,它根本不会收到任何“Authorization: Bearer [token]”标头。 我的环境配置:
ENV['simple-auth'] = {
authorizer: 'simple-auth-authorizer:token'
};
ENV['simple-auth-token'] = {
refreshAccessTokens: true,
timeFactor: 1000,
refreshLeeway: 300, // Refresh the token 5 minutes (300s) before it expires.
serverTokenEndpoint: 'https://localhost:8000/login',
crossOriginWhitelist:[
'http://localhost:4200',
'https://localhost:8000'
],
identificationField: 'user',
passwordField: 'password',
tokenPropertyName: 'token',
authorizationPrefix: 'Bearer ',
authorizationHeaderName: 'Authorization',
// headers: {},
};
我还尝试通过调用 jqXHR.setRequestHeader 来手动设置标头,覆盖我的登录路由中的授权函数,但没有成功:
authorize: function(jqXHR, requestOptions) {
var auth= "Bearer " + this.get('session').content.secure.Token;
console.log('Add authorization header ' + auth);
console.log( JSON.stringify(requestOptions));
jqXHR.setRequestHeader("Authorization", auth);
}
谁能告诉我我错过了什么? simple-auth-token 不应该自动添加标头吗? 谢谢你的帮助, 人。
【问题讨论】:
-
我刚刚发现,如果我使用单个主机,即如果我将 ember 应用程序放在 locahost:8000 并将 api 服务器保持在 locahost:8000/api,则会发送授权令牌。如果我将 ember 移至 localhost:4200(无论端口还是协议),则根本不会发送授权令牌。这不是 CORS 的问题:资源请求被发送到服务器,它错过的只是授权令牌。
-
你有想过这个吗?
标签: authentication ember.js jwt