I am doing authorization using ApiKey, and I want to get 401 Unauthorizedif the authorization data is not specified, and 403 Forbiddenif the authorization data is invalid. But I got it 500 Internal Server Errorin both situations.
security.yml
security:
providers:
api_key_user_provider:
entity:
class: RestBundle:RestUser
property: apikey
firewalls:
rest_api_area:
pattern: ^/api
stateless: true
rest_auth:
header: x-apikey
provider: api_key_user_provider
access_control:
- { path: ^/api, roles: ROLE_REST_USER }
RestUserListener.php
class RestUserListener implements ListenerInterface
{
protected $tokenStorage;
protected $authenticationManager;
private $header;
function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, $header)
{
$this->tokenStorage = $tokenStorage;
$this->authenticationManager = $authenticationManager;
$this->header = $header;
}
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
$apikey = $request->headers->get($this->header);
if (!$apikey) return;
$token = new RestUserToken();
$token->setUser($apikey);
$authToken = $this->authenticationManager->authenticate($token);
$this->tokenStorage->setToken($authToken);
return;
}
}
RestUserAuthenticationProvider.php:
class RestUserAuthenticationProvider implements AuthenticationProviderInterface
{
private $userProvider;
public function __construct(UserProviderInterface $userProvider)
{
$this->userProvider = $userProvider;
}
public function authenticate(TokenInterface $token)
{
$user = $this->userProvider->loadUserByUsername($token->getUsername());
if ($user)
{
$authenticatedToken = new RestUserToken($user->getRoles());
$authenticatedToken->setUser($user);
return $authenticatedToken;
}
throw new AuthenticationException("Apikey not found.");
}
public function supports(TokenInterface $token)
{
return $token instanceof RestUserToken;
}
}
RestUserToken is as simple as AbstractTokenit has no additional logic.
api_key_user_provider is the standard entity provider identified by the propertyApiKey RestUser
RestUserFactory also does not have additional magic inside, as in the official documentation