2016-06-01 4 views

答えて

2

あなたはこのような何かを行うことができ、トークンベースのコントロールしたい場合:

をあなたのインターセプタ:あなたのよう

angular.module('yourApp', []).config(function($httpProvider) { 
    $httpProvider.interceptors.push('YourHttpInterceptor'); 
} 

angular.module('yourApp').factory('YourHttpInterceptor', ['$q', '$window', 
function($q, $window) { 
    return {   
     'request': function(config) { 
      config.headers = config.headers || {}; 

      // If you have a token in local storage for example: 
      if ($window.localStorage.token) { 
       // Add the token to "Authorization" header in every request 
       config.headers.Authorization = 'Bearer ' + $window.localStorage.token; 
       // In your server you can check if the token is valid and if it's not, 
       // in responseError method you can take some action 
      } 


      // Handle something else 

      return config; 
     },  

     // Optional method 
     'requestError': function(rejection) { 
      // do something on request error 

      if (canRecover(rejection)) { 
       return responseOrNewPromise 
      } 
      return $q.reject(rejection); 
     },   

     // Optional method   
     'response': function(response) { 
      // do something on response success 
      return response; 
     }, 

     // optional method 
     'responseError': function(rejection) { 
      // Here you can do something in response error, like handle errors, present error messages etc. 

      if(rejection.status === 401) { // Unauthorized 
       // do something 
      } 

      if (canRecover(rejection)) { 
       return responseOrNewPromise 
      } 
      return $q.reject(rejection); 
     } 
    }; 
}]); 

そして、あなたのモジュールのconfigにインターセプタを登録しますthis postでトークンベースの認証がこの手順(ほとんどの場合)に従います:

  1. クライアントは、その資格情報(ユーザー名とパスワード)をサーバーに送信します。
  2. サーバーはそれらを認証し、有効期限のあるトークンを生成します。
  3. サーバは、以前に生成されたトークンを、メモリやデータベースなどのユーザ識別子を持つ何らかのストレージに格納します。
  4. サーバーは生成されたトークンをクライアントに送信します。
  5. すべての要求で、クライアントはトークンをサーバーに送信します。
  6. サーバーは、要求ごとに、着信要求からトークンを抽出し、トークンを使用してユーザー識別子をルックアップして、認証/承認を行うユーザー情報を取得します。
  7. トークンが期限切れの場合、サーバーは別のトークンを生成してクライアントに返します。
関連する問題