我是jQuery Mobile和Backbone.js的新手,并试图在客户端创建一个移动应用程序 - 使用基于django rest框架的API。
当我将我的用户名和密码发布到我的api时,生病{token: "<mytoken>"}
,我必须拦截并在我的应用程序的每个未来请求中添加到标题"Authorization: Token <mytoken>"
。我怎么能这样做?
我读过 Good idea to use REST token authentication for AJAX web apps?和 How use token authentication with Rails, Devise and Backbone.js?,但我仍然不明白如何将其整合到我的授权中。
有人可以帮助我吗?谢谢!
my login view:
var LoginView = Backbone.View.extend({
events: {
"click #login": "login",
},
initialize: function () {
this.template = $.tpl['login-form'];
},
render: function (eventName) {
$(this.el).html(this.template());
this.username = $("#username", this.el);
this.password = $("#password", this.el);
return this;
},
login: function () {
console.log('entered');
if (!this.username.val() || !this.password.val()) {
return false;
}
var user = new User({
username : this.username.val(),
password : this.password.val(),
});
user.save({}, {success: function() {
window.workspace.navigate('#transaction/list', { trigger: true });
return true;
}});
return false;
}
});
user model:
var User = Backbone.Model.extend({
defaults: {
username: "",
password: ""
},
url:"http://localhost/rest2/api-token-auth/"
});
template:
<div data-role="fieldcontain" class="ui-hide-label">
<input id="username" name="username" type="text" placeholder="username"/>
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<input name="password" id="password" type="text" placeholder="password"/></input>
</div>
<a name="login" id="login" data-role="button">login</a>
</div>
答案 0 :(得分:2)
像这样覆盖Backbone.sync。使用Backbone的每个请求都通过Backbone.sync
Backbone._sync = Backbone.sync
Backbone.sync = function(method, model, options) {
options = $.extend({
// In case the request is cross domain, keep these next 4 lines
crossDomain: true
, xhrFields: {
withCredentials: true
}
// Add the token to the request header
, beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Token ' + token);
}
}, options);
return Backbone._sync(method, model, options);
}
发布凭据时,您可以将令牌存储在localStorage中。我注意到我必须在重定向之前添加一个短暂的超时,以便脚本有时间将令牌存储在localstorage中。
user.save({}, {success: function(model, response) {
localStorage.setItem('access_token', response.token)
setTimeout(function(){
window.workspace.navigate('#transaction/list', { trigger: true}); }
, 100);
return true;
}});
并使用
从那里获取它, beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Token ' + localStorage.access_token);
}
以便在打开新的浏览器窗口或标签页时允许用户保持登录状态。