Token-Based Authentication API with PHP

Jyotishgher Astrology
By -
0

 Create a Basic PHP API with Token Authentication

Today we are going to create in the shortest time possible an API with PHP and authentication using tokens. Come, walk with me through the wonderful world of scripting, hack and slash.

Token-Based Authentication API with PHP

Understanding the Basics

Before we dive into the code, let's break down what we're aiming to build:

  1. Endpoint for User Registration: Users can sign up, providing their credentials.
  2. Endpoint for User Login: Users can log in with their credentials.
  3. Protected Endpoint: Once authenticated, users can access this endpoint.

Setting Up the Environment

Ensure you have PHP installed on your system. You'll also need a web server like Apache or Nginx. For this tutorial, we'll use PHP's built-in web server.

<?php

include_once($_SERVER['DOCUMENT_ROOT'] . "/header.php");

require __DIR__ . '/vendor/autoload.php';

use \Firebase\JWT\JWT;

use \Firebase\JWT\Key;

ini_set('display_errors', 1);

ini_set('display_startup_errors', 1);

error_reporting(E_ALL);

$secret_key = "Z4V-------------------------------------------------";

$headers = apache_request_headers();

if (isset($headers['Authorization'])) {

    $jwt = str_replace("Bearer ", "", $headers['Authorization']);

    try {

        // Validate JWT Token

        $decoded = JWT::decode($jwt, new Key($secret_key, 'HS256'));

        

        // Token is valid, proceed with the query

        $sql = oci_parse($conn, "SELECT * From Dual");

        oci_execute($sql);

        $result = array();

        $url = "http://yourdomain.com/image_long_raw.php?no="; // as per your requirement to show image

        while ($r = oci_fetch_array($sql, OCI_ASSOC + OCI_RETURN_NULLS)) {

            array_push($result, array(

     'NAME' => $r['NAME'],

    'ImagePath_Thumbnail' => $url . $r['NO']

            ));

        }

        echo json_encode(["status" => 200, "message" => "Access granted", "data" => $result]);

    } catch (\Firebase\JWT\ExpiredException $e) {

        echo json_encode(["status" => 401, "message" => "Token expired", "error" => $e->getMessage()]);

    } catch (\Firebase\JWT\SignatureInvalidException $e) {

        echo json_encode(["status" => 401, "message" => "Invalid signature", "error" => $e->getMessage()]);

    } catch (Exception $e) {

        echo json_encode(["status" => 401, "message" => "Access denied", "error" => $e->getMessage()]);

    }

} else {

    echo json_encode(["status" => 401, "message" => "Token not provided"]);

}

?>

Benefits of Securing with JWT

  1. Enhanced Authentication: JWT ensures only authenticated users can access the API.
  2. Tamper-Proof: The signature ensures token integrity.
  3. Efficient Authorization: Reusable token eliminates frequent login requests.
  4. Improved Security: Secure data in transit and validate token expiry on the client.

These changes ensure robust security and protect your application from unauthorized access and data breaches. This is a basic example. For production, you'll need to implement robust security measures, error handling, and database integration.

Keep Coding, Keep Learning!

Tags:

Post a Comment

0Comments

Post a Comment (0)