Laravel API using JWT authentication tutorial from scratch

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post i want to show you a tutorial about how to create API in Laravel also with by using JWT, If you are a beginner then i hope It will a very simple way to create and also it is pretty easy to understand how to create an API. So after this tutorial i hope you can make more secure and also complex your API. So you can learn here JWT authentication from back-end side. We need to learn how to works API from front-end and also in back-end side. Here i will give you both side fully example of how it works and how it’s use.

JWT stand for Json Web Token. JWT will helps us to create an authentication and also connect front-end and back-end function. JWT through you can create login and register API.

So first you need to install “tymon/jwt-auth” package in laravel application.

JWT Installation

At first need to fire following command on our terminal.

Installation Package
composer require tymon/jwt-auth

So after install this package, Now need to open config/app.php file and need to add service provider and aliase.

config/app.php

'providers' => [
	....
	'Tymon\JWTAuth\Providers\JWTAuthServiceProvider',
],
'aliases' => [
	....
	'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth'
],

So now we have to publish JWT configuration file, that way you can change configuration like token expire time etc. So, let’s need fire bellow command.

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"

Now at last on installation, you need to generate jwt key, need to fire bellow command on our terminal.

php artisan jwt:generate

Create API Route

Okay now you need to create a route for API, in bellow route you can see that here i use two middleware “api” and “cors”. cors is not mandatory, but when we call api and found like:

“Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://test.com/api/register. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).”

Then you have two must be create cors middleware by following link : Ajax – Cross-Origin Request Blocked in Laravel?

app/Http/routes.php

Route::group(['middleware' => ['api','cors'],'prefix' => 'api'], function () {
    Route::post('register', '[email protected]');
    Route::post('login', '[email protected]');
    Route::group(['middleware' => 'jwt-auth'], function () {
    	Route::post('get_user_details', '[email protected]_user_details');
    });
});

Now in above i will use also added jwt-auth for token is valid or not. So now we must need to create a jwt-auth middleware and at first need to fire following command.

php artisan make:middleware authJWT

On now you can need to check on Middleware(app/Http/Middleware) directory, you can find authJWT.php file and need to put bellow code on that file.

app/Http/Middleware/authJWT.php
namespace App\Http\Middleware;
use Closure;
use JWTAuth;
use Exception;
class authJWT
{
    public function handle($request, Closure $next)
    {
        try {
            $user = JWTAuth::toUser($request->input('token'));
        } catch (Exception $e) {
            if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
                return response()->json(['error'=>'Token is Invalid']);
            }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
                return response()->json(['error'=>'Token is Expired']);
            }else{
                return response()->json(['error'=>'Something is wrong']);
            }
        }
        return $next($request);
    }
}

Ok good, now need to register the new created middleware on Kernel.php(app/Http/Kernel.php) file and append following line.

app/Http/Kernel.php

namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
	...
	...
    protected $routeMiddleware = [
        ...
        'jwt-auth' => \App\Http\Middleware\authJWT::class,
    ];
}

Create Controller

Now here we will create a new controller that will manage all route and request. So at first need create “APIController” and need t put bellow code.

app/Http/Controllers/APIController.php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Hash;
use JWTAuth;
class APIController extends Controller
{
	

    public function register(Request $request)
    {        
    	$input = $request->all();
    	$input['password'] = Hash::make($input['password']);
    	User::create($input);
        return response()->json(['result'=>true]);
    }
    

    public function login(Request $request)
    {
    	$input = $request->all();
    	if (!$token = JWTAuth::attempt($input)) {
            return response()->json(['result' => 'wrong email or password.']);
        }
        	return response()->json(['result' => $token]);
    }
    

    public function get_user_details(Request $request)
    {
    	$input = $request->all();
    	$user = JWTAuth::toUser($input['token']);
        return response()->json(['result' => $user]);
    }
    

}

Read Also : How to create scroll to top of the page by jquery animate ?

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →