JWT stands for JSON Web Token. it is basically a feature of authenticating securely by making the authentic transfer between two web servers, which lets you safe access in a web or mobile application.
JSON Web Tokens has three parts, mainly separated by (.) Header, Payload, and Signature.
The header is made of two parts, which is as follows: Token type, which is JWT and Signing algorithm, such as HMAC SHA256 or RSA.
The Payload which is second part of the json web token comprises of claims. Claims are statements about the user, and it has three types, such as registered, public, and private claims.
The signature part is referred to as an encoded header, payload, and a secret. It is solely responsible for authenticating the message that wasn't changed along the way.
Here at Fixwebnode, as part of our Website Development Services, we regularly help our Customers to perform related Laravel Rest API authentication queries.
In this context, we shall look into how to build the rest APIs with jwt (JSON web token) authentication in laravel 8.
Table of contents [Show]
Steps to Build REST API with Laravel 8 using JWT Token (JSON Web Token)
1. Create Laravel 8 Application
To begin, Open command prompt and run the following command to install laravel 8 application:
$ composer create-project --prefer-dist laravel/laravel blog
2. Configure Database for Laravel Application
Now, Navigate root directory of your installed laravel restful authentication api with jwt tutorial project. Then open .env file and add the database details as per your database information:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=enter your database name here
DB_USERNAME=enter database username here
DB_PASSWORD=enter database password here
3. Install JWT Auth
Here, run the below command and install composer require tymon/jwt-auth package:
$ composer require tymon/jwt-auth
Next, Execute the below command in the console:
$ composer update
After successfully installing laravel jwt, you need to register providers.
To do so, Open config/app.php file and add the below code:
// config/app.php
'providers' => [
….
'Tymon\JWTAuth\Providers\JWTAuthServiceProvider',
],
'aliases' => [
….
'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth',
'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory',
],
Next, you need to install laravel to generate jwt encryption keys. This command will create the encryption keys needed to generate secure access tokens:
$ php artisan jwt:generate
Next, open JWTGenerateCommand.php (vendor/tymon/src/Commands/JWTGenerateCommand.php) file and paste this following code:
public function handle() {
$this->fire();
}
4. Register Middleware
JWT auth package comes with middleware which we can use. So register auth.jwt middleware in the app/Http/Kernel.php file:
protected $routeMiddleware = [
'auth.jwt' => 'auth.jwt' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',
];
5. Run Migration
Here, you need to do migration using the below command. This command creates tables in the database :
$ php artisan migrate
6. Create API's Route
Here, you need to create rest API routes for laravel restful authentication apis with jwt project.
To do this, navigate to the routes directory and open api.php. Then update the following routes into api.php file:
use App\Http\Controllers\API\JWTAuthController;
Route::post('register', [JWTAuthController::class, 'register']);
Route::post('login', [JWTAuthController::class, 'login']);
Route::group(['middleware' => 'auth.jwt'], function () {
Route::post('logout', [JWTAuthController::class, 'logout']);
});
7. Create JWT Auth Controller
Here, you need to create a controller name JWTAuthController. To do this, Use the below command and create a controller :
$ php artisan make:controller Api\JWTAuthController
Next, you need to create some methods in JWTAuthController.php. So navigate to app/http/controllers/API directory and open JWTAuthController.php file.
After that, update the following methods into your JWTAuthController.php file:
<?php
namespace App\Http\Controllers\API;
use JWTAuth;
use Validator;
use App\Models\User;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpFoundation\Response;
class JwtAuthController extends Controller
{
public $token = true;
public function register(Request $request)
{
$validator = Validator::make($request->all(),
[
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
if ($this->token) {
return $this->login($request);
}
return response()->json([
'success' => true,
'data' => $user
], Response::HTTP_OK);
}
public function login(Request $request)
{
$input = $request->only('email', 'password');
$jwt_token = null;
if (!$jwt_token = JWTAuth::attempt($input)) {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], Response::HTTP_UNAUTHORIZED);
}
return response()->json([
'success' => true,
'token' => $jwt_token,
]);
}
public function logout(Request $request)
{
$this->validate($request, [
'token' => 'required'
]);
try {
JWTAuth::invalidate($request->token);
return response()->json([
'success' => true,
'message' => 'User logged out successfully'
]);
} catch (JWTException $exception) {
return response()->json([
'success' => false,
'message' => 'Sorry, the user cannot be logged out'
], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
public function getUser(Request $request)
{
$this->validate($request, [
'token' => 'required'
]);
$user = JWTAuth::authenticate($request->token);
return response()->json(['user' => $user]);
}
}
Then open command prompt and run the following command to start developement server:
$ php artisan serve
8. Register Auth API Routes
Navigate to the routes/api.php file and register API routes for Laravel application, routes are powered by RouteServiceProvider within the group aligned with api middleware group:
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\JwtAuthController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('/signup', [JwtAuthController::class, 'register']);
Route::post('/signin', [JwtAuthController::class, 'login']);
Route::get('/user', [JwtAuthController::class, 'user']);
Route::post('/token-refresh', [JwtAuthController::class, 'refresh']);
Route::post('/signout', [JwtAuthController::class, 'signout']);
});
9. Use Postman to Test Auth REST API
Go to console and execute below command:
$ php artisan serve
Postman is a hassle free app to test the REST APIs, you can download Postman from here.
10. Register User in Laravel
Start the Postman app, set the HTTP method to POST, enter the API URL for registering the new user. Select Body from the tab options, within the form-data segment, enter name, email, password and password confirmation data and click on Send button.
You will see the response coming from the server about signing up a new user; you can check that user in your database’s User table.
11. Check Login Auth API
Add signin API to login the laravel app along with email and password in Postman app then click on send button. You will see the server response with user information, access_token, token_tupe and expires_in.
12. Get User Profile with JWT Token
Next, set the API method to GET, head over to Authorization section, select Type to Bearer Token add the access token that we received after making the Signin request.
13. Token Refresh API
Refresh JSON web token, enter the API in Postman app, paste the Bearer token within the Authorization section.
14. Test Sign-out API
Sign-out from Laravel app by destroying the JWT token.
[Need help to fix Laravel Website issues ? We can help you. ]
This article covers how to build basic authentication REST API and secure them with JSON web token. In fact, the Laravel JWT package is provided by laravel framework. so we can easily create and manage the API in laravel.