Lumen is a great framework to build an API off of, but it does not come with user authentication or authorization. I needed to create a small API that allowed users to create an account and access the service with a JWT. Quality information on how to pull that off with Lumen is not very well available- this article will provide a single reference point on building a simple user authentication and authorization system with JWTs on Lumen.
In this article I will teach you how to set up user authentication and authorization in Lumen. I will not teach you what Lumen or JWT is. I am going to assume you know what a they are or you would not be reading this article.
If you are following along, the prerequisite for what follows is:
- Running Lumen project
To see the complete code from this article, visit https://github.com/blobaugh/lumen-api-jwt-auth-example
This example includes a docker-compose.yml file that will get you up and running quickly.
For the JWT portion, we will be utilizing the excellent library from https://github.com/tymondesigns/jwt-auth
Install the JWT Library
We will be utilizing the JWT library by Sean Tymon. The library is installable as a composer package, and can be installed with the following command:
composer require tymon/jwt-auth
A secret needs to be generated to configure the JWT library, and added to the .env file. It can be generated with the following artisan command.
php artisan jwt:secret
The .env file was automatically updated with the key. The key will be used to sign all the JWT tokens.
There are now some steps we need to take to prep Lumen, before we can implement the user authentication portion.
To begin, open up the file bootstrap/app.php, then add or uncomment the following: