【问题标题】:How to intercept and add to header auth_token for each request?如何拦截并添加到每个请求的标头 auth_token?
【发布时间】:2013-11-28 16:13:59
【问题描述】:

我是 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>

【问题讨论】:

    标签: javascript jquery django backbone.js access-token


    【解决方案1】:

    像这样覆盖 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 中。我注意到我必须在重定向之前添加一个短暂的超时,以便脚本有时间将令牌存储在本地存储中。

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

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

    【讨论】:

    • 是的!谢谢,但我有一个小问题,如何拦截我的令牌?仅当我将令牌放入 'Authorization', 'Token ' + token 时,您的决定才有效。还是我错过了什么?
    • 我已经添加了关于如何在收到令牌时存储令牌的说明,如果这就是您的意思:)
    猜你喜欢
    • 1970-01-01
    • 2020-06-23
    • 2015-11-18
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多