2016-06-11 43 views
1

我使用科爾多瓦離子,這是由與的oauth2集成遠程服務器認證創建小移動應用程序。

首先,我試圖獲得acccess_token,然後使用該access_token我試圖訪問其他資源。

這就是我試過的。

function getToken(user){ 
    var username=user.userName; 
    var password = user.password; 
    var authResponse; 
    var access_token; 
    var headers = { 
     'Authorization': 'Basic ' + TOKEN_ENDPOINT.basicAuth, 
     //'Content-Type': 'application/x-www-form-urlencoded', 
     'Access-Control-Allow-Origin':'*' 
    } 
    $http.defaults.headers.common.Authorization='Basic ' + TOKEN_ENDPOINT.basicAuth; 
    $http({ 
     method: "POST", 
     headers: headers, 
     url: 'http://remote/oauth/', 
    }).then(function (data, status) { 
     if (status == '200') { 
      access_token=data.access_token; 
      console.log("Auth.signin.success!") 
      console.log(data); 
     } 
    }) 
    return access_token; 
} 

這是我想使用access_token

var goToProfile=function(user){ 
    var token = getToken(user); 
    if(token != null){ 
     $http({ 
      method:'POST', 
      url:(API_ENDPOINT.url+'/profile',user), 
      param:{access_token:token} 
     }).then(function(result){ 
      console.log(result.data.success); 
      console.log("Successfully signed in"); 
     }) 
    }else{ 
     console.log('dasd'); 
    } 
} 

所以問題是,getToken方法總是返回undefined。我可以看到access_token。所以我怎麼能得到access_token

+0

的問題是,你要編寫異步代碼,就好像是同步的。 – Casey

+0

感謝您的支持。所以我怎麼能讓它同步呢? – Ameger

回答

0

試試這個例子,修改代碼相應

$http({ 
    method: "post", 
    url: "http://localhost:8081/employee-connect/oauth/token", 
    data: "username=1234567891&password=chaitanya&grant_type=password&scope=read write&client_secret=my-secret-token-to-change-in-production&client_id=employeeConnectapp", 
    withCredentials: true, 
    headers: { 
     'Content-Type': 'application/x-www-form-urlencoded' 
    } 
    }) 
    .success(function(data) { 
     window.localStorage.setItem("token_type", data.token_type); 
     window.localStorage.setItem("token", data.access_token); 


      $http({ 
      method: "get", 
      url: "http://localhost:8081/employee-connect/api/articles", 
      withCredentials: true, 
      headers: { 
       'Accept' : 'application/json, text/plain, */*', 
       'Authorization' : ''+window.localStorage.getItem("token_type")+' '+window.localStorage.getItem("token") 
      } 
      }) 
       .success(function(data) { 
       $scope.news = data; 
       }) 
       .error(function(data, status) { 
       }); 

    }) 
    .error(function(data, status) { 
    }); 
+0

我不明白他爲什麼需要使用localStorage。 – Casey

+0

這只是我使用由Jhipster創建的oAuth2 api發送的一個Ionic應用程序的一個基本示例,我創建了 – abhi314

+0

您可以在不使用localStorage的情況下執行此操作,但最好將它放在localStorage中並且不要使用它,然後在需要時再發送令牌調用以解僱他的api電話 – abhi314