Batching tokens with Laravel, JWT and Angularjs

220 views Asked by At

I have an API written in Laravel and a front end written in Angularjs.

In order to authenticate I use JSON Web Tokens. As we know angularjs makes its ajax requests in a non-blocking i/o fashion.

For JWT, each request contains a Authentication token which goes to the server, the server checks if its valid, invalidates it and then gives a new token on the response to be used for the next request.

Since angular could make several requests at a time this means the chain of tokens does not work correctly.

Here is the angularjs plugin that I am using: https://github.com/lynndylanhurley/ng-token-auth#about-token-management

And here is the plugin for laravel I am using: https://github.com/tymondesigns/jwt-auth

The doco for that plugin gives a suggested solution in a Ruby plugin: https://github.com/lynndylanhurley/devise_token_auth

But I don't know ruby.

I require an example implementation of handling JWT on angular and PHP with consideration given to batch processing tokens.

1

There are 1 answers

0
Jamie On BEST ANSWER

You could do something like this:

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