header image

Krishnan's Personal Website


Home | Resume | Blog | Interesting Reads | Tutorials | Skills | Personal Projects | Books | Newsletters | Certifications | Fun | Connect with me


API Authentication in Laravel with JWT


Published On: May 30 2023
Written By: Krishnan Sethuraman
Category: Programming


I was working on a personal project and I came across a use case where I had to allow users to create an api key and use that key to authenticate some apis within the application. These apis will have to be used without user authentication and with just the generated api key.  

The personal project in this case is Indian Pincodes API. This is a rest api that provides the town/city and state of a particular pincode. Until this point this api was open to the world, which means that there was no authentication. A user would typically send a request and get a result. 

One fine day, in order to scratch an itch I decided to add authentication to this api. Jwt token was the way to go forward as I felt Oauth was not the right fit for this particular use case. 

All the online articles that I read as part of my research only covered Jwt token generation as part of user authentication. This is something I didn't want. According to my use case, the registered users will login into the web app and then generate their own api key which they will then use to authenticate apis. 

So I decided to go ahead and build my own logic. 

The first step was to have a library function encode and encode Jwt tokens. My preferred library to create Jwt tokens was a library that I found in a Twilio help article (I am 100% not sure how I found this library). You can find that in the  GitHub repo  linked below, in addition to the repo I have included with this article.

JWT Token Library

I used it to generate jwt tokens. These tokens were then stored in a table against specific users. 

Then I built a simple middleware which would validate the api key (aka Jwt token) for every API request. So if the Jwt token was valid the user would get a result else an error. 

 

With all this done I linked the middleware to the api route and voila, my api requests were now authenticated via an api key that was generated by the user inside his web console. 

Though I had to go against the ethos of not reinventing the wheel, I am glad that I was able to build this on my own as it gave me a clear understanding of the Laravel systems. 

The entire set of code that I used in my application is available in the following GitHub repository. 

JWT Authentication in Laravel