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

GHT API 验证器为 API 应用提供身份验证。

安装

使用 Composer 安装,运行 composer require greenhollowtech/ght-api-authenticator

用法

验证器设计用于与 GHT API 客户端 配合使用,解析和验证包含通过 Authorization 头部传递的 userkeyhash 值的请求。

验证器的最简单用法是验证已知密钥和密钥与当前 HTTP 请求

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...

很可能,您的应用程序将为每个用户存储 API 密钥和密钥。在验证请求之前,您可以首先获取授权凭证来查找请求用户的密钥和密钥。

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());
    ...

安全漏洞

您可以在验证过程中覆盖使用的凭证,请求本身以及 Authorization 头部的需求,以允许通过 POST 值、GET 查询字符串等方式传递凭证。请参阅 GHTApiAuthenticator 类的文档以获取所有详细信息。验证器不会强迫您保持安全和安全 - 请自行承担风险。