2015-04-03 122 views
0

一旦我用簡單的JavaScript客戶端創建了訪問令牌,就會從我的API中訪問數據時出現問題。使用Oauth使用Javascript訪問Api

這是我的Js應用程序對象,你可以看到我從我的api返回一個新的access_token - 這個工作正常到這一點。我將access_token存儲到app.AccessToken中,以供我在整個應用程序中使用的任何其他API調用中使用。但由於某種原因,當我要求任何迴應總是登錄頁面,所以基本上我正在重定向,當我嘗試訪問任何東西,即使我通過工作在最新access_token。

var app = (function(){ 

/** 
* Api 
* @type Object 
*/ 
var api = { 
    AccessToken : null, 
    views: {}, 
    models: {}, 
    collections: {}, 
    content: null, 
    router: null, 
    documents: null, 
    init: function() { 
     this.content = $("#content"); 
     this.documents = new api.collections.Documents(); 
     Backbone.history.start(); 
     return this; 
    }, 
    changeContent: function(el) { 
     this.content.empty().append(el); 
     return this; 
    }, 
    title: function(str) { 
     // set page title 
    } 
}; 

/** 
* ViewFactory 
* @type Object 
*/ 
var ViewFactory = { 
    documents: function() { 
     this.documentsView = new api.views.documents({ 
      model: api.documents 
     }); 
     return this.documentsView; 
    } 
}; 

/** 
* AppRouter 
* @type Object 
*/ 
var Router = Backbone.Router.extend({ 
    routes: { 
     '' : 'documents' 
    }, 
    documents: function() { 
     var view = ViewFactory.documents(); 
     api.changeContent(view.$el); 
     view.render(); 
    } 
}); 

/** 
* OAuth 
* @type Object 
* @return string 
*/ 
var OAuth = { 

    title : 'Js Client', 
    clientId : 'NTUxNTY4YWE1NWUxMzI4', 
    username : '[email protected]', 
    password : 'password', 

    init: function() { 
     var provision = OAuth.provision(); 
     if(provision.hasOwnProperty('success')) { 
      var authenticate = OAuth.authenticate(); 
      if(authenticate.hasOwnProperty('access_token')) { 
       api.AccessToken = authenticate['access_token']; 
      } 
     } 
    }, 

    provision: function() { 
     var response; 
     $.ajax({ 
      async: false, 
      url : 'http://customer-server-2.dev/oauth/provision/.json', 
      type : 'get', 
      data : { 
       title : OAuth.title, 
       client_id : OAuth.clientId 
      }, 
      success:function(data) { 
       response = jQuery.parseJSON(data); 
      }, 
     }); 
     return response; 
    }, 

    authenticate: function() { 
     var response; 
     $.ajax({ 
      async: false, 
      url : 'http://customer-server-2.dev/oauth/token.json', 
      type : 'get', 
      data : { 
       'grant_type' : 'password', 
       'username' : OAuth.username, 
       'password' : OAuth.password, 
       'client_id' : OAuth.clientId, 
      }, 
      success:function(data) { 
       response = data; 
      } 
     }); 
     return response; 
    }, 
} 

/** 
* Exercute & return 
*/ 
api.router = new Router(); 
OAuth.init(); 
return api; 

})(); 

回答

0

解決!我需要確保在Rest AppController上我需要定義$this->Auth->allow()關於api範圍內的操作。