Restful API In Laravel 5.6 Using Jwt Authentication



When I got a Laravel API kind of assignment first time, I am like stunned. Hmm !!! Well, every new bee will be the same. Hope this will give some idea for the beginners.

Before jumping, Am assuming that you have basic knowledge in

1.            Laravel
2.            Laravel middleware concepts.

Yea, That's it!!
Go Ahead ...

Overview

This article is mainly dealing with how to build restful API in laravel using JWT(JSON  Web Token). It is very easy and simple implementation in laravel. when you work with large application and you also want to make a mobile or android application for this project. you should write API layer or API for your application which helps to communicate with your android app and your live server.

Steps to implement

Step 1: Google it !!!

Yea, Simply google “Laravel API Jwt Authentication”. 


Step 2: Installing the Tymon/Jwt-auth package

Let’s install this package in our Laravel application. If you are using Laravel version 5.5 or above, run the following command to require a dev-develop version of jwt package.

 composer require tymon/jwt-auth:dev-develop --prefer-source

If you are using the laravel version 5.4 or less, run the following command

composer require Tymon/jwt-auth

Step 3: Make some changes in the config/app.php file

Open your config/app.php file and set service provider and their aliases.

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


Step 4: Publishing Configuration File

Publish the configuration file using the following command.

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


Above will publish the config file and generate a config/jwt.php configuration file.

If you want some custom configuration in it you should make in this file.

You don’t have many things to customize here like you are a beginner right?

There are 2 things probably you gonna edit.

ttl: Specify the length of time the JWT token is valid (in minutes).
user: User Model namespace,  


So I did  it like
For user modal :

   'user' => 'Modules\Api\Entities\User',
/*
  
|--------------------------------------------------------------------------
  
| User Model namespace
  
|--------------------------------------------------------------------------
  
|
  
| Specify the full namespace to your User model.
  
| e.g. 'Acme\Entities\User'
  
|
   */

   'user' => 'Modules\Api\Entities\User',


For token expiry:

/*
   |
--------------------------------------------------------------------------
   | JWT
time to live
   |
--------------------------------------------------------------------------
   |
   | Specify
the length of time (in minutes) that the token will be valid for.
   |
Defaults to 1 hour
   |
  
*/

   'ttl
' => 262800, // 6 months


Step 5: Generate JWT Token

We need to set a secret key in the config file, It’s a must.


Following is a helper command is to generate a random key.


php artisan jwt: secret


Wow !!! This is the coolest thing I found, In my early times with laravel. We have commands, and composer. If we need some new package or need to install a new thing, Just go to command line and run some commands nothing have to done manually.

Step 6: Creating Middleware

Create a middleware for JWT API.

Open your  app\Http\Middleware folder and create a file, Like for example mine is VarifyJWTToken.php. You can name this as your wish but follow naming conventions in php.    

Check out the following logic. 


namespace App\Http\Middleware;

use Closure;
use JWTAuth;
use Tymon\JWTAuth\Middleware\GetUserFromToken;

class VerifyJWTToken extends GetUserFromToken
{
   
/**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
   
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);
    }
}
Step 7: Registering Middleware

We need to register the created Middleware in app/Http/Kernel.php.

Add your middleware in protected $routeMiddleware.

 protected $routeMiddleware = [
    ...
   
'jwt.auth' => \App\Http\Middleware\VerifyJWTToken::class,
   
];
Step 8: Set up Routes

Laravel provides the routes/api.php file for write API route and this is best for manage all API route in it. so our web application route and API route not mix. So your api.php should be like.

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| 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!
|
*/
$api = app(
'Dingo\Api\Routing\Router');
$api->version(
'v1', function ($api) {
     
     
//Controller route
    $api->post(
'signin', 'Modules\Api\Http\Controllers\AuthController@signin');
   
    $api->group([
'middleware' => ['jwt.auth']], function($api)
    {
        ...
    }
    ....
}
Step 9: Write the Authentication Logic.

Hell yea!!! Done with the Base. This is all for login right? Here is mine

In Modules\Api\Http\Controllers\AuthController

public function signin(Request $request){
        $credentials = $request->only(
'email', 'password');
        $token =
null;
       
try {
           
if (!$token = JWTAuth::attempt($credentials)) {
               
return response()->json([
                   
'response' => 'error',
                   
'message' => 'invalid_email_or_password',
                ]);
            }
        }
catch (JWTAuthException $e) {
           
return response()->json([
               
'response' => 'error',
               
'message' => 'failed_to_create_token',
            ]);
        }
       
return response()->json([
           
'response' => 'success',
           
'result' => [
               
'token' => $token,
            ],
        ]);
    }
Step 10: Testing with Postman

Postman? Not a MARVEL character of course. Confused huh?

It’s a  commonly used API testing tool.

And if your output looks like this?



Cool !!!

Leave the else to App Developers, They will pass this returned token with every request from App. And a valid token will pass the middleware.

Be Careful with
Sometimes you make API and call it then you get the following error message

"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)."

Don’t worry man, Somehow I found a solution after long time research.

Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application.

Installation

Require the barryvdh/laravel-cors package in your composer.json and update your dependencies:

$ composer require barryvdh/laravel-cors

Group Middleware

If you want to allow CORS on a specific middleware group or route, add the HandleCors middleware to your group:

Of Course ! this what I need

So, I have done the edits in Kernal.php like

protected $middlewareGroups = [
   
'web' => [
      
// ...
    ],

   
'api' => [
       
// ...
        \Barryvdh\Cors\HandleCors::
class,
   
],
];
Worked… Eureka !!!!!!.

I am done !!!

Difficult ???

Keep going,

Tough Situations build strong people in the End.

Don't hesitate to get in touch with us for any kind of Laravel Development Service.

Comments

  1. ExpressTech Software Solutions is one of the best Laravel Development Company in India specialized in providing on demand striking web application development. Contact us : +91-9806724185 or Contact@expresstechsoftwares.com

    ReplyDelete

Post a Comment

Popular posts from this blog

Dependency Injection in PHP

Steps to do a file upload in Laravel Vapor

How to add your application as a sub-domain to Vapor