2016-06-01 7 views
3

저는 학생이고, 최근에는 angularJS 인터셉터로 작업하고 세션 관리를 제어하기 위해 개발하려고합니다. 나는 평균 스택 개발에 새로운 도움이 필요하다. 누구라도 angularJS의 세션 관리에 대한 실례를 가지고 있습니까?제어 세션에 angularjs 인터셉터를 개발하는 방법

정말 감사드립니다.

답변

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); 
     } 
    }; 
}]); 

그리고 당신의 모듈 설정에서

이 인터셉터를 등록 this post에서 토큰 기반 인증이이 단계 (거의 항상)를 따르는 것을 볼 수 있습니다 :

  1. 클라이언트가 자격 증명 (사용자 이름 및 암호)을 서버로 보냅니다.
  2. 서버가 인증하고 만료 날짜가있는 토큰을 생성합니다.
  3. 서버는 이전에 생성 된 토큰을 데이터베이스 또는 메모리와 같은 사용자 식별자가있는 일부 저장소에 저장합니다.
  4. 서버가 생성 된 토큰을 클라이언트에 보냅니다.
  5. 모든 요청에서 클라이언트는 토큰을 서버로 보냅니다.
  6. 각 요청에서 서버는 들어오는 요청에서 토큰을 추출하고 토큰으로 사용자 식별자를 검색하여 인증/권한 부여를 수행 할 사용자 정보를 얻습니다.
  7. 토큰이 만료 된 경우 서버는 다른 토큰을 생성하여 클라이언트로 다시 보냅니다.