Laravel 5 generate auth token using JWT

JWT is the most popular and secure package for creating the token for API access. Many times we need to create the API for mobile application or REST API on the Laravel project. Let’s see how we can create secure API using JWT on Laravel step by step.

JWT auth is the Laravel package for making secure API. JWT auth is working token base, first of all, we need to create JWT auth token for authenticating the user to access the API. After, token generating we need to pass that token on the every API request then JWT auth is verified the token if the token is not valid then the request is denied for accessing the API. Let’s see how we can setup the JWT auth on Laravel.

I hope you installed the Laravel if not first please installed the Laravel.

First of all, we install the JWT auth package on Laravel. So open your composer.json file and add the JWT auth package.

"require": {
    "tymon/jwt-auth": "0.5.*"
}

Then Run composer update command using the command prompt and wait still installing the package.

After installing the JWT auth package we need to register the provider and aliases on Laravel. So let’s open your config/app.php file for registering provide and aliases.

First of all, We register JWT provide.

Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,

Then we register Aliases.

'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class

Append the provide and aliases on your “app.php” file.

Then after we need to generate the configuration file of JWT auth package. first below command for generating the configuration.

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

Then after we need to generate the random key for JWT, which will be used to sign your token.

php artisan jwt:generate

The configuration of JWT is finished. Now, let’s create the controller for generating the token for API.

First of all, let’s create the route for generating the token. open route file and routes/web.php create the route for token generate.

Route::post('jwt/token', 'JwtauthController@generateAuthToken');

Now, we need to except the URL from verifying the CSRF token. let’s open Verify CSRF token file app/Http/Middleware/VerifyCsrfToken.php then append the URL on  $except variable like below.

'jwt/token',

Now, let’s create the controller for generating token so create new controller file at app/Http/Controllers/JwtauthController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class JwtauthController extends Controller
{

    public function generateAuthToken(Request $request){
        $credentials = $request->only('email', 'password');

        try {
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'Invalid Credentials'], 401);
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'Something went wrong please try again.'], 500);
        }

        return response()->json(compact('token'));
    }

}

Now, we are ready for creating the secure token for our API request. Now let’s send the request for generating the new token with email and password like below.

For testing the API request generally, I used the ‘POSTMAN’ plugin of chrome browser. Right now we send the JAVASCRIPT request for generating the token.

var form = new FormData();
form.append("email", "example@gmail.com");
form.append("password", "123456");

var settings = {
  "async": true,
  "url": "http://localhost:8000/jwt/token",
  "method": "POST",
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

If the user login detail is right the output like below.

{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODAwMC9qd3QvdG9rZW4iLCJpYXQiOjE1MDY3MDIzODQsImV4cCI6MTUwNjcwNTk4NCwibmJmIjoxNTA2NzAyMzg0LCJqdGkiOiJUZU9HckZNNW5QUWxaRVZLIn0.g8v3WA2EKD-ChOPFgoEnie1MtoNyZ0P5P_PJqRtFXAo"}

Now, let’s create the controller for verifying the JWT auth token and get user detail.

First of all, we create the route for the verifying the user token and return response. so let’s open routes/web.php file then write route.

Route::post('get/user', 'ApiController@getUser');

Now, except the URL from verifying CSRF token. let’s open the app/Http/Middleware/VerifyCsrfToken.php file and append URL $except variable.

'get/user',

Now, let’s create the controller for getting the user detail. create the new controller fileapp/Http/Controllers/ApiController.php then write the code for verifying the JWT auth token.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class ApiController extends Controller
{
    protected $user;
    public function __construct(){
        JWTAuth::parseToken();

        $this->user = JWTAuth::parseToken()->authenticate();
    }

    public function getUser(Request $request){
        return User::get();
    }

}

Now, let’s create the request for getting the users using the generated token. If the token is verified successfully then you can access the user using $this->user variable.

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:8000/get/user?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODAwMC9qd3QvdG9rZW4iLCJpYXQiOjE1MDY3MDIzODQsImV4cCI6MTUwNjcwNTk4NCwibmJmIjoxNTA2NzAyMzg0LCJqdGkiOiJUZU9HckZNNW5QUWxaRVZLIn0.g8v3WA2EKD-ChOPFgoEnie1MtoNyZ0P5P_PJqRtFXAo",
  "method": "POST",
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

If token verified successfully the output something like below.

 [{"id":1,"name":"John Cohen","email":"johncohen@gmail.com","created_at":"2017-09-25 16:38:01","updated_at":"2017-09-25 16:38:01","first_name":"John","last_name":"Cohen","mobile":"9999999999","country":"United State","state":"Montana","city":"Miles City","pincode":"59301"}]

If token verification is failed or token expired then you can get the exception about the token is expired or token is invalid.

If you face any problem after using this code write the comment below.