2015-06-11 40 views
0

我有一个用Laravel编写的API和一个用Angularjs编写的前端。Laravel,JWT和Angularjs的批处理标记

为了验证我使用JSON Web令牌。 正如我们所知,angularjs以非阻塞I/O方式发出ajax请求。

对于JWT,每个请求都包含一个身份验证令牌,该消息传递给服务器,服务器检查其是否有效,使其无效,然后在响应中为下一个请求提供新令牌。

由于角度一次可以发出多个请求,这意味着令牌链不能正常工作。

这里是我使用的angularjs插件: https://github.com/lynndylanhurley/ng-token-auth#about-token-management

这里是laravel插件我使用: https://github.com/tymondesigns/jwt-auth

该插件的DOCO给出一个Ruby插件的建议解决方案: https://github.com/lynndylanhurley/devise_token_auth

但我不知道红宝石。

我需要一个处理JWT on angular和PHP的示例实现,并考虑批处理令牌。

回答

0

你可以做这样的事情:

employeeAppModule.config([ 
     '$httpProvider', 
     function ($httpProvider) { 
      $httpProvider.interceptors.push(function() { 
       var token, headers, $cookies; 

       //inject cookies 
       angular.injector(['ngCookies']).invoke(['$cookies', function(_$cookies_) { 
        $cookies = _$cookies_; 
       }]); 

       return { 
        request: function (request) { 
         token = $cookies.get('jwt-token'); 
         headers = request.headers || (request.headers = {}); 
         request.headers = headers; 
         if(token != null && token != 'undefined') { 
          request.headers.Authorization = 'Bearer' + token; 
         } 
         return request; 
        }, 
        response: function (response) { 
         if (typeof response.data.result === 'undefined') { 
          return response; 
         } 

         if(response.status && response.status.code === 401) { 
          alert('token wordt verwijderd'); 
         } 

         if(response.data && response.data.result.token && response.data.result.token.length > 10) { 
          $cookies.put('jwt-token', response.data.result.token); 
         } 
         return response; 
        } 
       }; 
      }); 
     }]);