使用 Laravel、JWT 和 Angularjs 批处理令牌

Batching tokens with Laravel, JWT and Angularjs

我有一个用Laravel写的API和一个用Angularjs写的前端。

为了进行身份验证,我使用 JSON Web 令牌。 正如我们所知,angularjs 以非阻塞 i/o 方式发出其 ajax 请求。

对于 JWT,每个请求都包含一个发送到服务器的身份验证令牌,服务器检查其是否有效,使其无效,然后在响应中提供一个新令牌以用于下一个请求。

由于 angular 可以同时发出多个请求,这意味着令牌链无法正常工作。

这是我正在使用的 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

但是我不知道ruby。

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

你可以这样做:

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