gpt4 book ai didi

javascript - 如何为每个请求拦截并添加到 header auth_token?

转载 作者:行者123 更新时间:2023-11-30 17:45:34 25 4
gpt4 key购买 nike

我是 jQuery Mobile 和 Backbone.js 的新手,正在尝试在客户端创建移动应用程序 - 使用基于 django rest 框架的 API。

当我将我的用户名和密码发布到我的 api 时,我会得到 {token: "<mytoken>"} ,我必须拦截并添加到标题 "Authorization: Token <mytoken>"在我的应用程序的每个 future 请求中。我该怎么做?

我读过 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>

最佳答案

像这样覆盖 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);
}

您可以在发布凭据时将 token 存储在 localStorage 中。我注意到我必须在重定向之前添加一个短超时,以便脚本有时间将 token 存储在本地存储中。

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);
}

为了让用户在打开新的浏览器窗口或标签页时保持登录状态。

关于javascript - 如何为每个请求拦截并添加到 header auth_token?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20224853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com