Create JWT Based Authentication Endpoint With Laravel Lumen
Many modern applications today implemented JWT (JSON Web Token) based authentication, although there are some pros/cons around it, JWT still a popular token format among developers.
Lumen Version
Currently my application written in Lumen 7.0.3, if you are not sure which version you have just check it with command:
php artisan --version
Dependency
I’m using php-jwt library in this tutorial, you can run following command to install:
composer require firebase/php-jwt
Table Structure
I’m using MySQL 8.x, and my user’s table defined as follow:
CREATE TABLE `user` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(25) NOT NULL,
`password` varchar(100) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
or if you prefer migration script:
public function up()
{
Schema::create('user', function(Blueprint $table)
{
$table->increments('id');
$table->string('username', 25)->unique('username');
$table->string('password', 100);
$table->timestamps();
});
}
User Model
User model must implemented AuthenticatableContract and AuthorizableContract as Laravel standard for doing authentication.
JWT Secret
Add secret key to your your .env file, this key will be used to generate the token
JWT_SECRET=my-strong**secret!!!key
Auth Controller
The controller only have two methods plus one constructor, jwt() used to generate JWT token and authenticate() to perform authentication.
Register Route
Finally, create authentication url. Add following lines into routes/web.php:
$router->group(['prefix'=> 'auth'], function() use ($router) {
$router->post('login', [
'uses' => 'AuthController@authenticate'
]);
});
Testing
Now it’s time to check whether our endpoint is working or not, open postman or any other tool and make HTTP post request