How to send a token with every request using HTTP headers?

To send a token with every request using headers in your HTTP requests, you typically add the token to the Authorization header. Here’s a detailed explanation along with code samples in JavaScript for the frontend and PHP (CodeIgniter) for the backend:

// Assuming you have a token stored in localStorage
const token = localStorage.getItem('token');

// Make an HTTP request with the token in the Authorization header
fetch('https://example.com/api/resource', {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${token}`
  }
})
  .then(response => {
    // Handle response
  })
  .catch(error => {
    // Handle error
  });

In the frontend code:

  • Retrieve the token from localStorage or sessionStorage where it was stored after login.
  • Include the token in the Authorization header of the HTTP request using the Bearer authentication scheme.

Backend (PHP – CodeIgniter)

In your CodeIgniter application, you’ll need to intercept incoming requests to extract and validate the token. You can achieve this using middleware or by hooking into the request lifecycle. Here’s a sample implementation:

Middleware Approach:

// application/Middleware/AuthMiddleware.php

namespace App\Middleware;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Middleware\BaseMiddleware;

class AuthMiddleware extends BaseMiddleware
{
    public function before(RequestInterface $request, $arguments = null)
    {
        // Get the Authorization header from the request
        $authorizationHeader = $request->getHeaderLine('Authorization');
        
        // Extract the token from the header
        $token = str_replace('Bearer ', '', $authorizationHeader);

        // Validate the token (pseudo-code)
        if (!$this->isValidToken($token)) {
            return redirect()->to('/login'); // Redirect to login page or send error response
        }

        // Token is valid, continue with the request
        return $request;
    }

    // Add your token validation logic here
    private function isValidToken($token)
    {
        // Validate token against your authentication mechanism
        // For example, using Firebase JWT library or native PHP JWT library
        // Return true if valid, false otherwise
    }
}

In the backend code:

  • Create a middleware named AuthMiddleware that intercepts incoming requests.
  • Extract the token from the Authorization header using $request->getHeaderLine('Authorization').
  • Validate the token. If the token is valid, allow the request to proceed. Otherwise, redirect to the login page or send an error response.

Hook Approach:

// application/Config/Filters.php

public $aliases = [
    'auth' => \App\Filters\AuthFilter::class
];

// application/Filters/AuthFilter.php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        // Same logic as in AuthMiddleware::before()
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // No need for after() implementation if token validation is done in before()
    }
}

In the backend code:

  • Create a filter named AuthFilter with the same logic as in the AuthMiddleware::before() method.
  • Use this filter in your routes or globally to intercept requests and validate the token.

Conclusion:

With this setup, every HTTP request from the frontend will include the token in the Authorization header, and the backend will intercept and validate this token using middleware or filters. If the token is valid, the request proceeds; otherwise, the user is redirected to the login page or receives an error response.

To send a token with every request using headers in your HTTP requests, you typically add the token to the Authorization header. Here’s a detailed explanation along with code samples in JavaScript for the frontend and PHP (CodeIgniter) for the backend: In the frontend code: Backend (PHP – CodeIgniter) In your CodeIgniter application, you’ll need…

Leave a Reply

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