2017-02-02 3 views
0

私はAngular jとLarvel 5.4で作業しています。レスポンスアングルからトークンを取得する際に、すべてのヘッダにパスポートトークンを設定する方法js

私は角JSでの認証のためのログインコントローラを作成しており、そのコードは以下のようになります。

app.controller('LoginController',function($scope,$state) { 
$scope.vm.login = function() { 

    $http({ 
      method: 'POST', 
      url: apiUrl+'auth/token', 
      data: $.param($scope.vm.logDetails), 
      headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
     }).then(function(response) { 
      console.log(response.data.access_token); 
      if(response.data.access_token) {      
       $state.go('dashboard.masters_userroles'); 
      } 
      else { 
       alert("Your credentials is wrong"); 
      } 
     }); 
} 
}); 

私はそれのためにインターセプタを作成しました。しかし、ヘッダーを設定することはできません。

.factory('tokenInjector',function($window){ 
return { 
    //For each request the interceptor will set the bearer token header. 
    request: function($config) {    
     if($window.sessionStorage.getItem('userInfo-token')) 
     { 
      var token=$window.sessionStorage.getItem('userInfo-token'); 
      console.log(token); 
      //set authorization header 
      $config.headers['Authorization'] = 'Bearer '+token; 
      return $config; 
     } 
    } 
} 
}) 
.config(function ($httpProvider) { 
    $httpProvider.interceptors.push('tokenInjector'); 
}) 

これはError: $compile:tpload Error Loading Templateのようなエラーです。

ここで、コンソールでは、コントローラでトークンを受信しました。今度はすべてのリクエストのヘッダーを$ stateProviderに設定したいと思います。では、トークンを保存するためにはどのような機能を作成する必要がありますか?

+0

http://stackoverflow.com/a/27136594/796400 –

+0

@RaghuVenmarathoorどのように私は動的にトークンを設定することができますか? –

+0

?私は理解できませんでした。インターセプタを使用して、そのトークンをすべての要求に設定できます。 –

答えて

0

機能を実現するには、2つのことを行う必要があります。

1)受け取ったトークンを一部のストレージ(LocalStorage、SessionStorage、CookieStorage)に保存します。あなたが望む誰でも。

それぞれについて、

sessionStorage.setItem(token, angular.toJson(response.data.access_token)); 

2)あなたがにあなたのヘッダーに保存されているトークンを提供している作る要求します。そのためには、$http Interceptorsを使用してください。この目的のためにファクトリを作成することができます。

angular.module('app').factory('tokenInjector',function(){ 
    return { 
    config.headers['Bearer'] = sessionStorage.getItem(angular.fromJson(token)); 
    return config; 
    } 
}) 

その後で、あなたの.configあなたが$httpProviderサービスを介して、あなたのトークンインジェクターを使用したいあなたのアプリで明確にしなければなりません。

angular.module('app').config(function ($httpProvider) { 
    $httpProvider.interceptors.push('tokenInjector'); 
}); 
+0

設定に関連するエラーが表示されます。セッションでトークンを設定して工場に戻しましたが、未定義に戻ります。 –

関連する問題