JWT Awesome Killer Use Cases

Tue Feb 27 2018

{.content-preview-title}

You got yourself your new feature to work on, another login system, log service, social plugin etc.

While you are talking to your team about the new feature, dozens of thoughts and ideas are running through your mind and you just want to run back to your keyboard.

Does that sound familiar?

I assume it is, as this is what we all do Ha Ha 😂

Now that far ago I discovered JWT, or in plain words:

Json Web Token

What The Hack is JWT ?!

The first use case you get to think of and surely this is what the community is talking about is authentication.

Surely JWT is a great tool for keeping your backend stateless and still authenticating your users.

I’ll share with you 2 more features I implemented with JWT and maybe they could inspire you to more use cases that will help you solve more problems 🙂

Redirection With No Storage {#redirectionwithnostorage}

As we all have those link redirectors that simply track your visit and send you to the appropriate page.

So the most basic one is having the destination inside the url and you are done.

But what if someone inserts there a malicious url and then send the redirector url to users?

So the users will think this link is solid as it is for a respective company like yourselves but then he gets redirected to who knows where.

Previous solution we had is simply having and ID in the url and when that ID appears we look it up in the DB and get the destination url.

Works great and solves the problem.

But.

Why should I waste precious time and resources for touching the DB??

So I used the JWT for storing the destination url and the user ID.

Now the backend gets the token, parses its validity and then redirects the user. No DB checks no nothing.

Example for JWT data:

{
    dest_url: “https://tzookb.com”,
    user: 11,
    exp: 123232131
}

You can see that I can easily get and track which user clicked the link.

Where should I redirect him and if I want I can add expiration to make this link expire.

Authenticate From The Url {#authenticatefromtheurl}

Let’s say you have a forgot password process, and what we always did is store an hash key that will send the user and when he clicks the email link he will get redirected to a page with that key.

Now in the backend we check that key in the DB and if it’s there we will allow the user to change passwords.

But again we have an un needed DB call.

We can use JWT again, and add the expiration to be in 2 hours, 24 hours whatever. So when the user clicks we can check for his JWT make sure it’s valid and assigned to him and we are good to go.