[Latest News][6]

B.Sc.CSIT
Blogs
Laravel
Learn
News
Rentonnepal
Technology
A Complete Online Magazine

AddThis

Laravel API using JWT authentication tutorial from scratch example

In this post i want to share you how to create API in Laravel 5.2 with using JWT, If you are beginner then It is a very simple way to create and it is pretty easy to undestand how to create API. After this you can make more secure and complex your API. you can learn JWT authentication from back-end side. we have to learn how to works API from front-end and back-end side. i give you both side fully example how it works and use.



JWT stand for Json Web Token. JWT will helps to create authentication and connect front-end and back-end function. JWT through we can create login and register API. So first we have to install "tymon/jwt-auth" package in laravel 5.2.

JWT Installation

First fire following command on your terminal.

Installation Package

composer require tymon/jwt-auth

After install this package, Now open config/app.php file and add service provider and aliase.

config/app.php

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

Now we need to publish JWT configration file, that way we can change configration like token expire time etc. so, let's fire bellow command.

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

At last on installation, we have to generate jwt key, fire bellow command on your terminal.

php artisan jwt:generate

Create API Route

Now we require to create create route for API, in bellow route you can see i use two middleware "api" and "cors". cors is not mandatory, but when you 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 Larave 5?.

app/Http/routes.php

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


In above i use also added jwt-auth for token is valid or not. so we must need to create jwt-auth middleware and first fire following command.

php artisan make:middleware authJWT

On now you can check on Middleware(app/Http/Middleware) directory, you can find authJWT.php file and 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, now register 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

Here we have to create controller that will manage all route request. so first create "APIController" and put bellow code.

app/Http/Controllers/APIController.php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\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]);
    }
    
}

Test API from Front-end

Don't forgot to change http://learnl52.hd = your site url.

Now we are ready to check our API from front-end side. i did make jquery ajax request example but you can also call API in angularjs. first fire register api that will return just success if user created success fully.

Call Register API

$.ajax({
url: "http://learnl52.hd/api/register",
dataType: "json",
type: "POST",
data: {"name":"HD","email":"test@gmail.com","password":"123456"},
success: function (data) {
alert("user created successfully")
}
});

Now you can fire login API, this API will return token in result if, email and password will not wrong. that token you have to pass in all other route that way you can identify this user is current login user so fire following way:

Call Login API

$.ajax({
url: "http://learnl52.hd/api/login",
dataType: "json",
type: "POST",
data: {"email":"test@gmail.com","password":"123456"},
success: function (data) {
alert(data.result)
}
});

At last we can fire get_user_details API, This API will take only one paramete token, token is that you find on login API. this API will return all users details if your token is valid, if token is not valid then return error message. fire ajax like this way:

Call Get User Details API

$.ajax({
url: "http://learnl52.hd/api/get_user_details",
dataType: "json",
type: "POST",
data: {"token":your toke here},
success: function (data) {
console.log(data)
}
});

No comments:

Post a Comment

Start typing and press Enter to search