JSON Web Token Authentication for Laravel

Custom developmentCustom web applicationLaravel
JSON Web Token Authentication for Laravel

Laravel is a free, open-source PHP web framework built by Taylor Otwell based on the Symfony framework. It is designed for building online applications that follow the model-view-controller (MVC) architectural paradigm.

The choice of authentication method in your Laravel application depends on the nature of your project. When it comes to picking the right approach, consider the specific requirements of your application. Sanctum presents options for both session-based and token-based authentication, which is particularly useful for securing Single-Page Applications (SPAs). On the other hand, Passport employs JSON Web Token (JWT) authentication by default and supports full OAuth 2.0 authorization.

If your goal is to implement token-based authentication adhering to the JWT standard, minus the supplementary OAuth features, then Laravel’s JWT authentication is the optimal choice. This approach provides a lightweight and efficient solution for securing your application.

 

Step 1: Install the package via composer

 

   composer require tymon/jwt-auth

 

Step 2: Add service provider

 

Add the service provider to the providers array in the config/app.php config file for Laravel 5.4 or below

 

‘providers’ => [

Tymon\JWTAuth\Providers\LaravelServiceProvider::class

]

 

Step 3: Publish the config file package

 

php artisan vendor:publish –provider=”Tymon\JWTAuth\Providers\LaravelServiceProvider

Now you have a config/jwt.php file that allows you to configure the basics of this package.

 

Step 4: Generate the secret key

 

It is the key that will be used to sign your tokens.

php artisan jwt:secret

This will update your .env file with something like 

JWT_SECRET=cHnJintjfSI24wDUtfNfdvtot4yvAKsg1G1gLCpvlgrKo29D84jeJAu6DQsCIKfv

 

Step 5: Update the User Model

 

Need to implement the  use Tymon\JWTAuth\Contracts\JWTSubject;  on your model, which requires that you implement the 2 methods getJWTIdentifier() 

 & getJWTCustomClaims()

The following example should provide you with an understanding of how this might be structured. Feel free to adjust it according to your requirements.

<?php


namespace App;


use Illuminate\Foundation\Auth\User as Authenticatable;

use Tymon\JWTAuth\Contracts\JWTSubject;



class User extends Authenticatable implements JWTSubject

{

use Notifiable;



/**

* Get the identifier that will be stored in the subject claim of the JWT.

*

* @return mixed

*/

public function getJWTIdentifier()

{

return $this->getKey();

}



/**

* Return a key value array, containing any custom claims to be added to the JWT.

*

* @return array

*/

public function getJWTCustomClaims()

{

return [];

}

 

Step 6: Configure the Auth guard

 

Here we are telling the api guard to use the jwt driver, and we are setting the api guard as the default.

'defaults' => [ 

'guard' => 'api', 

'passwords' => 'users', 

], 

... 

'guards' => [ 

'api' => [ 

'driver' => 'jwt', 

'provider' => 'users'

]

]

Now we can use the  Laravel’s built in Auth system, with jwt-auth

 

Methods

 

The following methods are available on the Auth guard instance

Multiple guard If the newly created ‘api’ guard is not set as a default guard or you have defined multiple guards to handle authentication, you should specify the guard when calling auth().

 

$token = auth(‘api’)->attempt($credentials);

attempt()Attempt to authenticate a user via some credentials

$token = auth()->attempt($credentials);

 

login()Log a user in and return a jwt for them

 

$user = User::first(); 

$token = auth()->login($user);

 

  • user()Get the currently authenticated user,If the user is not then authenticated, then null will be returned.

$user = auth()->user();

  • UserOrFail() – Get the currently authenticated user or throw an exception.

 

try { 

$user = auth()->userOrFail(); 

} 

catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) 

{ 

// do something 

}
  • logout() Log the user out, which will invalidate the current token and unset the authenticated user.

auth()->logout();

 // Pass true to force the token to be blacklisted “forever”

auth()->logout(true);

 

  • refresh()Refresh a token, which invalidates the current one

$newToken = auth()->refresh(); 

// Pass true as the first param to force the token to be blacklisted “forever”. 

// The second parameter will reset the claims for the new token 

$newToken = auth()->refresh(true, true);

 

  • invalidate()Invalidate the token (add it to the blacklist)

auth()->invalidate(); 

// Pass true as the first param to force the token to be blacklisted “forever”. auth()->invalidate(true);

 

  • tokenById() Get a token based on a given user’s id.

$token = auth()->tokenById(123);

 

  • Adding custom claims

$token = auth()->claims([‘foo’ => ‘bar’])->attempt($credentials);

 

  • Set the token explicitly

$user = auth()->setToken(‘eyJhb…’)->user();

 

  • Set the request instance explicitly

$user = auth()->setRequest($request)->user();

 

  • Override the token ttl

$token = auth()->setTTL(7200)->attempt($credentials);

 

Laravel’s integration of JSON Web Token authentication through jwt-auth offers a reliable and efficient solution to secure user interactions within your application. By following steps, you can easily integrate JWT authentication into your Laravel project, particularly in versions 5.2 and above.

FAQ

Laravel is a free and open-source PHP web framework created by Taylor Otwell, built upon the Symfony framework. Its main purpose is to simplify and accelerate web application development by providing a structured and organized environment.

JWT authentication is a lightweight and efficient method for securing applications. In Laravel, it's recommended when you want to implement token-based authentication adhering to the JWT standard without needing the additional OAuth features provided by Passport.

You can set the token explicitly using setToken() and the request instance using setRequest(). For example:

To set the token: auth()->setToken('eyJhb...')->user()
To set the request instance: auth()->setRequest($request)->user()

Yes, you can override the token TTL using the setTTL() method: auth()->setTTL(7200)->attempt($credentials).

Leave a Reply

Your email address will not be published. Required fields are marked *

3 × five =

2hats Logic HelpBot