greenhollowtech/ght-api-authenticator

2.0.0 2016-01-01 08:47 UTC

This package is auto-updated.

Last update: 2024-08-29 04:25:24 UTC


README

The GHT API Authenticator provides authentication in API applications.

Installation

To install with Composer, run composer require greenhollowtech/ght-api-authenticator.

Usage

The authenticator is designed to be used in counterpart with the GHT API Client, parsing and validating requests that contain user, key and hash values passed via the Authorization header.

The simplest use of the authenticator is to validate a known key and secret against the current HTTP request:

use GHT\ApiAuthenticator\GHTApiAuthenticator;

// Determine the expected API key and secret used by the client making the request
$apiKey = 'someKnownKey';
$apiSecret = 'someKnownSecretNotPassedInTheRequest';

// Validate the credentials in the current request
try {
    GHTApiAuthenticator::validate($apiKey, $apiSecret);
}
catch (\Exception $e) {
    // Don't let this hacker in!
    error_log('Request failed. ' . $e->getMessage());
    return;
}

// The request is validated, do something nice...

Quite possibly, your application will have API keys and secrets stored for each user. You can first grab the Authorization credentials to look up the requesting user's key and secret before validating the request.

use GHT\ApiAuthenticator\GHTApiAuthenticator;

// Get the requesting user's credentials
try {
    $credentials = GHTApiAuthenticator::getCredentials();
}
catch (\Exception $e) {
    // Authorization header is missing!
    error_log('Request failed. ' . $e->getMessage());
    return;
}

// Look up the User with whatever method is provided by your application
$user = $userRepository->findByUsername($credentials['api-user']);
// (you would validate your User object here, too, eh?)

// Validate the credentials in the current request with the User's key and secret
try {
    GHTApiAuthenticator::validate($user->getApiKey(), $user->getApiSecret());
    ...

Security Holes

You can override the credentials used in the validation, the request itself, and the Authorization header requirement to allow credentials passed via POST values, the GET query string, et cetera. See the documentation in the GHTApiAuthenticator class for all the nitty gritty. The authenticator does not force you to be safe and secure - manipulate at your own risk.