How can I restrict API access for API Keys
In PHP Application, I’ve created following middleware to validate API Key:
$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);
But I couldn’t find solution to identify from which URL(source) the API request is coming from. The API Key could be used by developers or any 3rd party integrating services like Zapier.
Can anyone help me to identify source of request coming from so that I could restrict the access?
In backend, I could define the URL for provided API Key but I do not know how could I prevent unauthorized access.
I do not want to use OAuth2 i.e. client/secret
from Laravel Questions and Answers https://laravelquestions.com/php/how-can-i-restrict-api-access-for-api-keys/
via Lzo Media
No comments:
Post a Comment