Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Configure Laravel JWT Authentication to Get Secure Data Transmission Across Platforms

June 12, 2019

3 Min Read
laravel jwt
Reading Time: 3 minutes

Hey, guys, I am back with a new article on my Laravel series. In one of my previous articles, I have demonstrated to you about how to create a REST API in Laravel and using Laravel passport for API authentication. As you know, REST API is a powerful web service that uses various HTTP methods (GET, PUT, POST, DELETE) for transmitting data across platforms, so it’s really important to master its configuration in Laravel for building and deploy better cross-platform apps on any Laravel hosting.

In this Laravel JWT auth tutorial, I will demonstrate to you about how to use Laravel JWT tokens for API authentication for the same Todo App that we have used in the previous article.

What is JWT?

JSON Web Token (JWT) is an authentication token through which we can securely transmit data between third-parties as a JSON object. The token usually remains valid for 3600s or one hour. Most of the recently developed API’s are using JWT for their API authentication.

Let’s quickly get started with our own, and see how to configure it in a Laravel application.

Installing Laravel JWT Authentication Package

To begin with this Laravel JWT auth tutorial, we need to first install the Tymon JWT package using the composer for adding JWT auth in Laravel.

composer require "tymon/jwt-auth:1.0.0-rc.3"

Once it is installed, publish its config by running the following command:

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

Now, run the following command to generate a secret key for generating Laravel JWT tokens.

php artisan jwt:secret

Next, open config/auth.php directory and under API inside guards, add the given driver for Laravel JWT authentication as shown below:

'guards' => [

      'web' => [

          'driver' => 'session',

          'provider' => 'users',

      ],

      'api' => [

          'driver' => 'jwt',

          'provider' => 'users',

      ],

  ],

Now, instead of using passport, our application will be using Laravel JWT tokens for all the Todo API authentication.

Lightning Fast Laravel Hosting With 24×7 Tech Support

We Take Care of Your Hosting Hassles To Let You Focus More On The Business

Creating API For Getting Laravel JWT Auth Token

The next step is to create a login route via which we will send Laravel JWT tokens to our users through which they will authenticate other APIs. Let’s generate a new API controller and create a login method in it. For this, you must create a function which will send a generic response to all the users.

protected function sendResult($message,$data,$errors = [],$status = true)

  {

      $errorCode = $status ? 200 : 422;

      $result = [

          "message" => $message,

          "status" => $status,

          "data" => $data,

          "errors" => $errors

      ];

      return response()->json($result,$errorCode);

  }

After creating the function, it’s time to create our login method which will take email and password and will return a JWT token along with its expiry.

public function login(Request $request)

  {

      $data = $request->all();

      $errors = [];

      $data = [];

      $message = "";

      $status = true;

      $validator = Validator::make($data,[

          'email' => 'required',

          'password' => 'required',

      ]);

      if ($validator->fails()) {           

          $status = false;

          $errors = $validator->errors();

          $message = "Login Failed";

      }

      $credentials = $request->only("email", "password");

      if (! $token = auth('api')->attempt($credentials)) {

          $status = false;

          $errors = [

              "login" => "Invalid username or password",

          ];

          $message = "Login Failed";

      }else{

          $message = "Login Successfull";

          $data = [

              'access_token' => $token,

              'token_type' => 'bearer',

              'expires_in' => auth('api')->factory()->getTTL() * 60

          ];
      }

      return $this->sendResult($message,$data,$errors,$status);
  }

Next, we will update our previous login route in routes/api.php file with new login controller.

Route::post('login','LoginController@login');

These JWT tokens will now be used as a bearer token for all the API authentication processes.

Testing

Now, let’s use our login API to generate JWT token:

We can use this newly generated token as a bearer token for other API’s.

Final Words

Laravel JWT provides a secure route to transmit data across platforms, as it comprises of a header and end-to-end signature that ensures fast and secure representation of data between two parties.

In the above demonstration, I have used my previous REST API article and changed its API authentication to Laravel JWT authentication. This shows how easy it is to switch to Laravel JWT authentication and why using JSON Web Token in Laravel is a better option.

If you still have some questions regarding this article, or want to contribute more on this topic, feel free to give your suggestions below in the comments section.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Launch Laravel apps with 1-Click Install. Painless Server Management

Deploy your apps on optimized Laravel hosting servers.

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling. You can email him at shahroze.nawaz@cloudways.com

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!