How do I authenticate API requests (JWT, OAuth2) in PHP?

Authenticating API requests is a crucial step in ensuring that only authorized users have access to certain functionalities. In this guide, we explore two commonly used methods: JSON Web Tokens (JWT) and OAuth2. Both techniques provide secure authentication for your PHP applications, allowing you to work with APIs efficiently.

1. Authenticating with JSON Web Tokens (JWT)

JSON Web Tokens are a compact, URL-safe means of representing claims to be transferred between two parties. Here's an example of how to implement JWT authentication in PHP:

<?php use Firebase\JWT\JWT; // Set the JWT secret key $secretKey = 'your-256-bit-secret'; // Create a function to generate JWT function generateJWT($userId) { global $secretKey; $payload = [ 'iat' => time(), 'exp' => time() + (60 * 60), // 1 hour expiration 'userId' => $userId ]; return JWT::encode($payload, $secretKey); } // Example of generating a token $token = generateJWT(123); echo json_encode(['token' => $token]); ?>

2. Authenticating with OAuth2

OAuth2 is another popular authorization framework that allows third-party services to exchange information without sharing credentials. Here’s a basic pattern to authenticate using OAuth2 in PHP:

<?php // Include the OAuth2 library require 'vendor/autoload.php'; use League\OAuth2\Client\Provider\GenericProvider; $provider = new GenericProvider([ 'clientId' => 'your-client-id', 'clientSecret' => 'your-client-secret', 'redirectUri' => 'http://your-redirect-url.com', 'urlAuthorize' => 'https://provider.com/oauth2/authorize', 'urlAccessToken' => 'https://provider.com/oauth2/token', 'urlResourceOwnerDetails' => 'https://provider.com/resource' ]); // Handling the OAuth2 flow if (!isset($_GET['code'])) { $authorizationUrl = $provider->getAuthorizationUrl(); // Store the state generated for CSRF protection $_SESSION['oauth2state'] = $provider->getState(); header('Location: ' . $authorizationUrl); exit; } else { // Check for the state in the callback if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { unset($_SESSION['oauth2state']); exit('Invalid state'); } // Get access token $accessToken = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); echo 'Access Token: ' . $accessToken->getToken(); } ?>

API Authentication JWT OAuth2 PHP API Security