CakePHP Programming

CakePHP and token based auth (with Angular JS)

This article will show you how to set up a Json Web Token with CakePHP and Angular. This blog post is not a complete step by step tutorial but shows you the concept of the JWT Token and a high-level implementation. To follow the instructions in this article it is assumed that you know how to work with REST and JSON Views in CakePHP and Composer.

This is actually pretty easy by using php-jwt and modifying Ceerams TokenAuthenticate adapter for CakePHP. I’ve modified the nice working TokenAuthenticate adapter to work with JWT. You’ll need to add firebase/php-jwt to your composer.json or add the library otherwise to your application. You can find the JwtTokenAuthenticate for CakePHP 2.x on Github, it is part of my BzUtils plugin.

So what is the important difference between JWT and a regular Token?

The JWT token is encrypted and contains the actual user data. Usually a token is stateless and you would have to look up the user based on the token generated after login in your database. That’s what the original component did until I’ve modified it to work with JWT. The JWT token eliminates that need because it contains the actual user data, or whatever else data you want to add to it, and encrypts it. Decrypting the token every request is more efficient than querying the DB every request to lookup the user based on the token.

Pay attention to no bloating the token with unnecessary data, just store what you really need, usually the users id, username and maybe email and some authorization specific things like a role. The issue with bloating the token is that your server might not respond properly or won’t respond at all. This is because HTTP does not define any header size limit but most web servers limit the size of headers they accept. For example in Nginx it is 8KB, Apache default limit is 8KB, in IIS it’s 16K. The server will return a 413 Entity Too Large error if the headers size exceeds that limit.

To use the component add this to your AppController::beforeFilter(), you’ll still need the Form Authenticate to do the login.

Your login function has to make use of the JWT lib as well to encode the token, remember, we’re dong RESTful calls and return JSON and don’t access this via the browser directly!

This is the AngularJS component that deals with the token data. Please note that the second request right after the login is just for demonstration purpose to demonstrate that the token works by making an immediate request to a protected action.