Slim framework is used to create REST API, In my last post, I explain how to create Rest API using slim. In this post, I will explain how to make your REST API secure using JSON Web Token (JWT). There is lots of information already on the web about JSON Web Token (JWT) Authentication so we will not duplicate it here but in a nutshell, it allows authenticating users against a single token instead of the more commonly used username/password. You can simply follow below step to create REST API with Slim.


Secure your php webservices using slim JWT


Install Slim framework

You can install Slim using composer which is the best way to setup, open terminal and run below command.

Else if your composer install globally then use this command

Install required dependencies

After setup Slim, we need to add some dependencies which we can use to generate JWT

I am using PSR-7 JWT Authentication Middleware for this post.

Slim JWT Auth setup

If you are using Apache server you need to update your project .htaccess open your  .htaccess file in the editor and replace the code with below code

Now go to your project src folder and edit middleware.php file in this file we can add our middleware in which we define all our settings, there are lots of options available with this plugin if you want to read about them please follow this link. Now add this below code into your middleware.php 

In above code, we call our JwtAuthentication class in which we can set some parameter like path, secret key, Path which we need to ignore, error, callback etc. Copy above code into your middleware.php. 

After adding above code you can now edit your routes.php which is also inside your src folder in this we can create or routes and handle user request generate token for the user. You can create no of routes depend upon your need but for this sample, I create 4 routes as shown below code snippet. 

In first routes, we can create token through which we can access other routes and I also create /not-secure route for this route we don’t need any token. Please check the demo video to check working of these routes. You can also try this in your REST Client like PostMan or Advanced REST Client.


Demo API Link:-

Hope this post helps you create your secure REST API using JWT Auth.

If this post helps you to understand working with Android Volley library, then please subscribe, our blog Also do Like our Facebook Page or Add us on Twitter.