In some cases, it may be necessary to make sure that whoever is trying
to access the functions or data has the necessary permissions to do
that. For example, an extension may provide a remote interface that
allows for manipulating sensitive data. See “Exercise 3. Plesk Entities
and
Authentication”
for an example.
Method
pm_Auth::isValidCredentials()
can be used to confirm authentication in such a case.
The following example shows how authentication is performed using the
credentials extracted from the HTTP request header.
namespace PleskExtExampleMiddleware;
use PsrHttpMessageResponseInterface;
use PsrHttpMessageServerRequestInterface;
class BasicAuth
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{
if ($request->hasHeader('Authorization')) {
list($login, $password) = $this->parseAuthorizationHeader($request->getHeaderLine('Authorization'));
if ($login && $password) {
if (pm_Auth::isValidCredentials($login, $password)) {
return $next($request->withAttribute('login', $login), $response);
}
}
}
return $next($request, $response);
}
private static function parseAuthorizationHeader($header)
{
if (strpos($header, 'Basic') !== 0) {
return [null, null];
}
$parsed = explode(':', base64_decode(substr($header, 6)), 2);
if (count($parsed) < 2) {
return [null, null];
}
return $parsed;
}
}
Another
example.