2013-11-26 2 views
0

저는 jQuery Mobile과 Backbone.js가 새로 도입되어 클라이언트 쪽에서 모바일 애플리케이션을 만들려고합니다 - 장고 rest 프레임 워크에 기반한 API를 사용하십시오. 각 요청에 대해 헤더 auth_token을 가로 채고 추가하는 방법은 무엇입니까?

난 내 API에 내 이름 & 비밀번호를 POST

, 병이 나는 차단해야하고 내 응용 프로그램의 각 미래의 요청에 "Authorization: Token <mytoken>" 헤더에 추가 {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> 

답변

1

다음과 같이 Backbone.sync를 재정의하십시오. 백본과 각 요청은 자격 증명을 게시 할 때 로컬 스토리지에있는 토큰을 저장할 수 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); 
} 

거기로부터 페치.

+0

예! 고마워,하지만 약간의 질문이 있는데, 내 토큰을 어떻게 가로 챌까? 당신의 결정은 내 토큰을''Authorization ','Token '+ token'에 넣을 때만 작동합니다. 아니면 어딘가에 놓친 거 있니? – aphex

+0

토큰을받을 때 토큰을 저장하는 방법에 대한 설명을 추가했습니다. – brunettdan

관련 문제