Skip to content

Instantly share code, notes, and snippets.

@johannessteu
Created February 22, 2019 10:59
Show Gist options
  • Save johannessteu/f50674a4f8ffc3e9560bb72a8b5c4993 to your computer and use it in GitHub Desktop.
Save johannessteu/f50674a4f8ffc3e9560bb72a8b5c4993 to your computer and use it in GitHub Desktop.
Flow JWT auth
<?php
class JwtApiTokenProvider extends AbstractProvider
{
/**
* @Flow\Inject
* @var PolicyService
*/
protected $policyService;
/**
* @Flow\InjectConfiguration(package="Your.Package", path="Api.sharedSecret")
*/
protected $secret;
/**
* Returns the class names of the tokens this provider is responsible for.
*/
public function getTokenClassNames()
{
return [JwtApiToken::class];
}
public function authenticate(TokenInterface $authenticationToken)
{
$credentials = $authenticationToken->getCredentials();
if (!is_array($credentials) || !isset($credentials['jwt'])) {
$authenticationToken->setAuthenticationStatus(TokenInterface::NO_CREDENTIALS_GIVEN);
return;
}
$jwtPayload = null;
try {
$jwtPayload = (array)JWT::decode($credentials['jwt'], $this->secret, ['HS256']);
} catch (\Exception $e) {
$authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS);
}
if ($jwtPayload === null || !isset($jwtPayload['accountIdentifier'])) {
$authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS);
return;
}
$account = $this->createTransientAccount($jwtPayload['accountIdentifier']);
$authenticationToken->setAccount($account);
$authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
}
/**
* @param $accountIdentifier
* @param array $roleIdentifiers
* @return Account
*/
protected function createTransientAccount($accountIdentifier)
{
$account = new Account();
$account->setAccountIdentifier($accountIdentifier);
$account->addRole($this->policyService->getRole('Your.Package:ApiUser'));
$account->setAuthenticationProviderName($this->name);
return $account;
}
}
<?php
class JwtApiToken extends AbstractToken implements SessionlessTokenInterface
{
/**
* The jwt credentials
*
* @var array
* @Flow\Transient
*/
protected $credentials = ['jwt' => ''];
/**
* @param ActionRequest $actionRequest
* @return void
*/
public function updateCredentials(ActionRequest $actionRequest)
{
if ($actionRequest->getHttpRequest()->hasHeader('X-Jwt')) {
$this->credentials['jwt'] = $actionRequest->getHttpRequest()->getHeader('X-Jwt');
$this->setAuthenticationStatus(self::AUTHENTICATION_NEEDED);
}
}
}
Neos:
Flow:
security:
enable: true
authentication:
providers:
JwtApiTokenProvider:
provider: Your\Package\Authentication\Provider\JwtApiTokenProvider
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment