public function authenticate(HttpServletRequestInterface $servletRequest, HttpServletResponseInterface $servletResponse)
{
// check if auth header is not set in coming request headers
if ($servletRequest->hasHeader(Protocol::HEADER_AUTHORIZATION) === false) {
// stop processing immediately
$servletRequest->setDispatched(true);
$servletResponse->setStatusCode(401);
$servletResponse->addHeader(Protocol::HEADER_WWW_AUTHENTICATE, $this->getAuthenticateHeader());
return false;
}
// load the raw login credentials
$rawAuthData = $servletRequest->getHeader(Protocol::HEADER_AUTHORIZATION);
// set auth hash got from auth data request header and check if username and password has been passed
if (strstr($credentials = base64_decode(trim(strstr($rawAuthData, " "))), ':') === false) {
// stop processing immediately
$servletRequest->setDispatched(true);
$servletResponse->setStatusCode(401);
$servletResponse->addHeader(Protocol::HEADER_WWW_AUTHENTICATE, $this->getAuthenticateHeader());
return false;
}
// get out username and password
list($username, $password) = explode(':', $credentials);
// query whether or not a username and a password has been passed
if ($password === null || $username === null) {
// stop processing immediately
$servletRequest->setDispatched(true);
$servletResponse->setStatusCode(401);
$servletResponse->addHeader(Protocol::HEADER_WWW_AUTHENTICATE, $this->getAuthenticateHeader());
return false;
}
// set username and password
$this->username = new String($username);
$this->password = new String($password);
// load the realm to authenticate this request for
/** @var AppserverIo\Appserver\ServletEngine\Security\RealmInterface $realm */
$realm = $this->getAuthenticationManager()->getRealm($this->getRealmName());
// authenticate the request and initialize the user principal
$userPrincipal = $realm->authenticate($this->getUsername(), $this->getPassword());
// query whether or not the realm returned an authenticated user principal
if ($userPrincipal == null) {
// stop processing immediately
$servletRequest->setDispatched(true);
$servletResponse->setStatusCode(401);
$servletResponse->setBodyStream('Unauthorized');
$servletResponse->addHeader(Protocol::HEADER_WWW_AUTHENTICATE, $this->getAuthenticateHeader());
return false;
}
// add the user principal and the authentication type to the request
$servletRequest->setUserPrincipal($userPrincipal);
$servletRequest->setAuthType($this->getAuthType());
return true;
}