2Hats . 4 minutes
August 21, 2023

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’ => [

TymonJWTAuthProvidersLaravelServiceProvider::class

]

 

Step 3: Publish the config file package

 

php artisan vendor:publish –provider=”TymonJWTAuthProvidersLaravelServiceProvider

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 TymonJWTAuthContractsJWTSubject;  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.

 

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.

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.

 

  • 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.

What is Laravel and its purpose in web development?

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.

What is JSON Web Token (JWT) authentication in Laravel, and when is it recommended?

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.

How can I set the token and request instances explicitly in Laravel JWT authentication?

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()

Is it possible to override the token's time-to-live (TTL) in Laravel JWT authentication?

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

blog
Greetings! I'm Aneesh Sreedharan, CEO of 2Hats Logic Solutions. At 2Hats Logic Solutions, we are dedicated to providing technical expertise and resolving your concerns in the world of technology. Our blog page serves as a resource where we share insights and experiences, offering valuable perspectives on your queries.
Aneesh ceo
Aneesh Sreedharan
Founder & CEO, 2Hats Logic Solutions
Subscribe to our Newsletter
Arsha Contact

    Stay In The Loop!

    Subscribe to our newsletter and learn about the latest digital trends.