Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

API Authentication - PHP Development

Introduction

API authentication is a critical aspect of web services. It ensures that the API endpoints are accessed securely and only by authorized clients. This tutorial will cover various methods of API authentication in PHP, including Basic Authentication, OAuth, and JWT (JSON Web Tokens).

Basic Authentication

Basic Authentication is a simple authentication scheme built into the HTTP protocol. The client sends HTTP requests with the Authorization header that contains the word Basic followed by a base64-encoded string username:password.

Example:

Below is an example of how to implement Basic Authentication in PHP:

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>
                    

OAuth Authentication

OAuth is an open standard for access delegation, commonly used as a way to grant websites or applications limited access to user information without exposing passwords.

Example:

An example of OAuth 2.0 implementation in PHP:

<?php
require 'vendor/autoload.php';
session_start();

$provider = new \League\OAuth2\Client\Provider\GenericProvider([
    'clientId'                => 'your-client-id',
    'clientSecret'            => 'your-client-secret',
    'redirectUri'             => 'your-redirect-uri',
    'urlAuthorize'            => 'https://provider.com/oauth2/authorize',
    'urlAccessToken'          => 'https://provider.com/oauth2/token',
    'urlResourceOwnerDetails' => 'https://provider.com/oauth2/resource'
]);

if (!isset($_GET['code'])) {
    $authorizationUrl = $provider->getAuthorizationUrl();
    $_SESSION['oauth2state'] = $provider->getState();
    header('Location: ' . $authorizationUrl);
    exit;
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
    unset($_SESSION['oauth2state']);
    exit('Invalid state');
} else {
    $token = $provider->getAccessToken('authorization_code', [
        'code' => $_GET['code']
    ]);
    try {
        $resourceOwner = $provider->getResourceOwner($token);
        $values = $resourceOwner->toArray();
        print_r($values);
    } catch (Exception $e) {
        exit('Failed to get resource owner: ' . $e->getMessage());
    }
}
?>
                    

JWT Authentication

JSON Web Tokens (JWT) are a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is digitally signed using JSON Web Signature (JWS).

Example:

Example of a JWT implementation in PHP using the Firebase JWT library:

<?php
require 'vendor/autoload.php';
use \Firebase\JWT\JWT;

$key = "example_key";
$payload = array(
    "iss" => "http://example.org",
    "aud" => "http://example.com",
    "iat" => 1356999524,
    "nbf" => 1357000000
);

$jwt = JWT::encode($payload, $key);
$decoded = JWT::decode($jwt, $key, array('HS256'));

print_r($decoded);
?>