This API was built for the Quotes app at the repo below.
- Step 1: Create new project and install jwt-auth
- Step 2: Add JWT Provider and Facades
- Step 3: Set Up Routes
- Step 4: Set Up Database
- Step 5: Register and Verify Email Address
- Step 6: Log User In and Out
- Step 7: Recover Password
- Step 8: Testing
Create Laravel project
laravel new JWTAuthentication
Open composer.json and update the require object to include jwt-auth
"require": {
"php": ">=5.6.4",
"laravel/framework": "5.4.*",
"laravel/tinker": "~1.0",
"tymon/jwt-auth": "0.5.*"
}
Then, run
composer update
We’ll now need to update the providers array in config/app.php with the jwt-auth provider. Open up config/app.php, find the providers array located on line 138 and add this to it:
Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,
Add in the jwt-auth facades which we can do in config/app.php. Find the aliases array and add these facades to it:
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class
We also need to publish the assets for this package. From the command line:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
After you run this command you will see a new file in the config folder called jwt.php. This file contains settings for jwt-auth, one of which we need to change right away. We need to generate a secret key which we can do from the command line:
php artisan jwt:generate
You’ll see that after running this command we get a new value next to’secret’ where “changeme” was before.
Register the jwt.auth and jwt.refresh middleware in app/http/Kernel.php
protected $routeMiddleware = [
...
'jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',
'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken',
];
Open up routes/api.php.
Route::post('register', 'AuthController@register');
Route::post('login', 'AuthController@login');
Route::post('recover', 'AuthController@recover');
Route::group(['middleware' => ['jwt.auth']], function() {
Route::get('logout', 'AuthController@logout');
});
Since we are going to allow users to create their accounts within the application, we will need a table to store all of our users. Thankfully, Laravel already ships with a migration to create a basic users table, so we do not need to manually generate one. The default migration for the users table is located in the database/migrations directory.
We need to add an extra column to the users table.
Available on my blog.
Available on my blog.
Available on my blog.
Available on my blog.
Available on my blog.