在PHP应用程序中,我创建了以下中间件来验证API密钥:
$apiKeyValueFromHeader = $request->header('Authorization');
$apiKeyValueFromQuery = $request->get('api_key');
if (empty($apiKeyValueFromHeader) && empty($apiKeyValueFromQuery)) {
throw new ApiKeyNotFoundException("API Key Not Found");
}
//Get API_KEY from header
$apiKeyFromHeader = null;
if ( ! empty($apiKeyValueFromHeader)) {
$bearer = explode(' ', $apiKeyValueFromHeader);
$apiKeyValue = $bearer[1];
$apiKeyFromHeader = $this->isApiKeyVerifiedFromHeader($apiKeyValue);
}
//Get API_KEY from QueryString
if (empty($apiKeyFromHeader)) {
$apiKeyFromQuery = $this->isApiKeyVerifiedFromQuery($apiKeyValueFromQuery);
if (empty($apiKeyFromQuery)) {
throw new InvalidApiKeyException("Unauthorized Access!");
}
$apiKey = $apiKeyFromQuery;
} else {
$apiKey = $apiKeyFromHeader;
}
$apiKey->update([
'last_used_at' => Carbon::now(),
'last_ip_address' => $request->ip(),
]);
$apikeyable = $apiKey->apikeyable;
$request->setUserResolver(function () use ($apikeyable) {
return $apikeyable;
});
$request->apiKey = $apiKey;
event(new ApiKeyAuthenticated($request, $apiKey));
return $next($request);
但我找不到解决方案来确定API请求来自哪个URL(源)。开发人员或任何第三方集成服务(如Zapier)可以使用API密钥。 任何人都可以帮我确定来自的请求来源,以便限制访问吗?
在后端,我可以定义提供的API密钥的URL,但我不知道如何防止未经授权的访问。
我不想使用OAuth2即客户端/秘密
答案 0 :(得分:0)
Please see passport documentation here
您可以为特定的第三方/来源创建特定用户。并且将为每个用户分配唯一令牌。您可以通过它来限制未经授权的访问,以及您可以识别哪个第三方正在访问API