Showing posts with label JWT. Show all posts
Showing posts with label JWT. Show all posts

Sunday, September 13, 2020

Laravel JWT Authentication


Laravel JWT Authentication

To use JWT you must know about the below Features : 

Introduction

JWT is an authentication token by which we can easily transfer data between the third parties or for example when we use Laravel API we have secure our data through JWT Token. Generally, it is valid for 3600 sec. or 1 Hour. Most of the recent application development using it for API authentication for example Mobile, Web, Cloud, IoT for user identification, verification and information security. 

The Structure of JWT

JWT has 3 below parts : 

Header

    This is where JWT’s cookies are located. The standard is defined as follows.

    
        "alg": "HS256",
        "typ": "JWT"
    }

Alg: Where it determines the Cryptographic Algorithm for JWT. Supported Algorithms vary depending on the language you use. You can review supported Algorithms via jwt.io.

Typ: Indicates that the Header type used is JWT.

Payload

Although there are some standards here, it is the part that contains the data we want to carry in general. To mention some standard keys;

iss (issuer): Publisher
sub (subject): Subject
exp (expiration time): Expiration date
nbf (not before time): Before this Date
iat (issued at the time): Created on

Signature

This is the part where the Key is used to create the JWT. The header is encrypted with the specified encryption method.

~~~

Except for the signature part of the JWT you produce, the data can be read in it. Simply decode the Base64. But you cannot make any changes to the information in the content because the key will become unusable.


Let's have look how can we install and use it in our application


To install JWT we need to first install Tymon JWT Package using the composer to add it in Laravel

composer require tymon/jwt-auth

After installation is done need to publish its configuration

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

Now run the below command to generate the secret key

php artisan jwt:secret

After the above command opens the file "config/auth.php" inside guards in API section add the driver as jwt to use it for all API requests.

'guards' => [
      'web' => [
          'driver' => 'session',
          'provider' => 'users',
      ],
      'api' => [
          'driver' => 'jwt',
          'provider' => 'users',
      ],
  ],
 
Now, our application will be using Laravel JWT tokens for all the API authentication.

Creating API to get Laravel JWT Authentication Token

The next step is to create a login route through 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 that will send a common response to all the users.

  function commonResponse($custom_message,$data,$errors = [],$status = true)
    {
        $result = [
            "message" => $custom_message,
            "status" => $status,
            "data" => $data,
            "errors" => $errors
        ];

        return response()->json($result, 200);
    }
  

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


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 = "Something went wrong, Login Failed email or password missing";
      }

      $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->commonResponse($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.

Summary 

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

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

Integration of Queue in Laravel

Integration of Queue in Laravel Introduction Laravel Queue is to enhances the laravel application performance and provides a smooth proc...