Commit c4354331 authored by Ad Schellevis's avatar Ad Schellevis

(mvc) add api auth to base controller

parent b096c21e
......@@ -28,6 +28,8 @@
*/
namespace OPNsense\Base;
use OPNsense\Core\ACL;
use OPNsense\Auth\AuthenticationFactory;
/**
* Class ApiControllerBase, inherit this class to implement API calls
* @package OPNsense\Base
......@@ -66,8 +68,47 @@ class ApiControllerBase extends ControllerRoot
*/
public function beforeExecuteRoute($dispatcher)
{
// TODO: implement authentication for api calls, at this moment you need a valid session on the web interface
// handle authentication / authorization
if (!empty($this->request->getHeader('Authorization'))) {
// Authorization header send, handle API request
$authHeader = explode(' ', $this->request->getHeader('Authorization'));
if (count($authHeader) > 1) {
$key_secret_hash = $authHeader[1];
$key_secret = explode(':', base64_decode($key_secret_hash));
if (count($key_secret) > 1) {
$apiKey = $key_secret[0];
$apiSecret = $key_secret[1];
$authFactory = new AuthenticationFactory;
$authenticator = $authFactory->get("Local API");
if ($authenticator->authenticate($apiKey, $apiSecret)) {
$authResult = $authenticator->getLastAuthProperties();
if (array_key_exists('username', $authResult)) {
$acl = new ACL();
if (!$acl->isPageAccessible($authResult['username'], $_SERVER['REQUEST_URI'])) {
$this->getLogger()->error("uri ".$_SERVER['REQUEST_URI'].
" not accessible for user ".$authResult['username'] . " using api key ".
$apiKey
);
} else {
// authentication + authorization successful, pass
return true;
}
}
}
}
}
// not authenticated
$this->response->setStatusCode(401, "Unauthorized");
$this->response->setContentType('application/json', 'UTF-8');
$this->response->setJsonContent(array(
'status' => 401,
'message' => 'Authentication Failed',
));
$this->response->send();
return false;
} else {
// handle UI ajax reuests
// use authentication of legacy OPNsense to validate user.
if (!$this->doAuth()) {
return false;
......@@ -87,7 +128,7 @@ class ApiControllerBase extends ControllerRoot
$this->getLogger()->error("no matching csrf found for request");
return false;
}
}
}
/**
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment