Slim3 Framework Authorization with JWT (JSON Web Tokens)

In this post, I will show how you can secure your Slim3 Framework-based applications using JSON Web Token (JWT). To know more about JWT and How it works visit the official website(

Download & Install

We gonna use composer to download and install the Slim Framework. The easiest way to start working with Slim is to create a project using Slim-Skeleton as a base by running this bash command:

Replace [my-app-name] with the desired directory name for your new application.

You can then run it with PHP’s built-in web server:

While running built-in web server you can access the application at: http://localhost:8080. If you head over to the browser with this URL you should get following output:

Connect to database

We gonna use MySQL as a database engine, so lets open src/settings.php file and add follwing array to settings array.

After placing your database settings, lets open src/dependencies.php file and inject database object into container with following code:

Now you can access this database connection instance with $this->db.

JWT Authentication

We gonna use tuupola/slim-jwt-auth library to handle JWT tokens. So let install it with composer, fire up the terminal and change the directory to project root and issue following composer command

After installation, open the src/settings.php file and append the followign JWT setttings array to existing settings array.

That’s it.

Now open your src/middleware.php file and add following code.

We have configured the middleware to auth check only the URLs contains the /api. If you want to pass multiple patterns pass them in an array format.

Open your src/routes.php file and define new route for login as shown below –

On the successful login, it will return JWT token. This method is pretty straightforward, first, we are validating the user with email and password, if the request is valid we are generating the JWT auth token. The user has to send this token in the header(Authorization: Bearer ) in order to get access to the protected routes/URLs.

Let’s define another route, it’s not public route, you need to send Authorization token to get access to it. As I mentioned above this URL is staring with /api so the user must authenticate to access this page.

My user table structure and its sample data:

How to deploy slim framework on CPanel

Note: Here my encrypted password is [email protected]

How to test

We gonna use Adanced RESt client to test apis, below are the screen shot of it.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.