Created
October 29, 2019 04:58
-
-
Save angelxmoreno/5d58b51ee54a0c0630a5a45620e4cfe2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Authentication\Authenticator; | |
use ArrayAccess; | |
use Authentication\Authenticator\FormAuthenticator; | |
use Authentication\Authenticator\Result; | |
use Authentication\Identifier\IdentifierInterface; | |
use Cake\Utility\Security; | |
use Firebase\JWT\JWT; | |
use Psr\Http\Message\ResponseInterface; | |
use Psr\Http\Message\ServerRequestInterface; | |
use RuntimeException; | |
/** | |
* Class ApiAuthenticator | |
* @package App\Authentication\Authenticator | |
*/ | |
class ApiAuthenticator extends FormAuthenticator | |
{ | |
protected $_defaultConfig = [ | |
'loginUrl' => null, | |
'urlChecker' => 'Authentication.Default', | |
'fields' => [ | |
IdentifierInterface::CREDENTIAL_USERNAME => 'username', | |
IdentifierInterface::CREDENTIAL_PASSWORD => 'password' | |
], | |
'algorithm' => 'HS256', | |
'secretKey' => null, | |
]; | |
/** | |
* JsonAuthenticator constructor. | |
* @param IdentifierInterface $identifier | |
* @param array $config | |
*/ | |
public function __construct(IdentifierInterface $identifier, array $config = []) | |
{ | |
parent::__construct($identifier, $config); | |
if (empty($this->_config['secretKey'])) { | |
if (!class_exists(Security::class)) { | |
throw new RuntimeException('You must set the `secretKey` config key for API authentication.'); | |
} | |
$this->setConfig('secretKey', Security::getSalt()); | |
} | |
} | |
public function authenticate(ServerRequestInterface $request, ResponseInterface $response) | |
{ | |
$result = parent::authenticate($request, $response); | |
return $result->isValid() | |
? new Result($this->buildData($result->getData()), Result::SUCCESS) | |
: $result; | |
} | |
/** | |
* @param null|array|ArrayAccess $data The identity data | |
* @return array | |
*/ | |
protected function buildData($data) | |
{ | |
$jwt = $this->buildJwt($data); | |
return [ | |
'jwt' => $jwt, | |
'id' => $data->id | |
]; | |
} | |
/** | |
* @param null|array|ArrayAccess $data The identity data | |
* @return string | |
*/ | |
protected function buildJwt($data) | |
{ | |
return JWT::encode([ | |
'sub' => $data->id, | |
], | |
$this->getConfig('secretKey'), | |
$this->getConfig('algorithm') | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment