Blog
Words about design, the industry, and everything in between.

Tokens for Authentication

Posted on

Something that I’ve started experimenting recently with is token-based authentication. Since I’ve been using more JavaScript and less PHP, I figured I can try using tokens in a RESTful API instead of sessions on the server. Instead of using a framework like OAuth (which I highly recommend using), I tried to recreate the token process. Here’s what I came up with.

This is usually how the process works: A user logs in, and a token is generated. The token is stored on the client (usually in a session, lately also as a local storage object). Then, to call an API, the view also sends the token. The server checks the integrity of the token and returns the relevant response. Each token contains a “private key” of sorts that only the server could’ve created. JWT does this really well. This my how I did it while playing:

A hashed version of the user unique key (a primary key like ID or, like I used, username) along with the date of 2 days into the future. In PHP, I wrote it like this:

$token = md5($input["username"] . date("Ymd", strtotime("+2 days")) . "secretkey123");

In this case, the non-hashed string looks like anand20160216secretkeyq123. I use this particular one because it’s going to be unique for every user (username) and it has a “secret” key. I chose +2 days because of how I’m checking for integrity:

When an API request is sent, the username is sent too, and the server knows the date. So we create two strings, username + date 1 day in the future + “secret” key, and another with the date 2 days into the future. So if a user logs in at 11:00 pm, the key works for 25 hours, and if a user logs in at 1:00 am, it works for 47 hours. Either way, a key works for at least one day and at most two days. This is good because we don’t want the key to work for more than a day or two.

Why this is bad

This is bad because we have no way of killing the token if a session is ended. When a user logs out and logs in again at the same, essentially the same key is generated because it’s dependent only on the server date. It works as a science experiment, but a fully-developed and tested framework like JWT or OAuth works for real-life projects.