I'm following along the docs about creating a custom api key authentication for certain urls but I think there's something missing.
If I just return;
from the ::createToken()
method a AuthenticationCredentialsNotFoundException
gets thrown and I'm handling that in my custom exception controller. The message in the exception is:
A Token was not found in the SecurityContext.
It's still forcing me to create a token. I tried removing the pattern
section in the config but that didn't do anything. I'd expect, for the config below, that any endpoints matching ^/admin
would optionally be authenticated. Ie. Authentication is not required, but will happen if api key is present.
What am I doing wrong?
Here's my security.yml
file
security:
encoders:
Symfony\Component\Security\Core\User\User: plaintext
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
providers:
in_memory_provider:
id: app.in_memory_user_repository
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
secured_area:
pattern: ^/admin
stateless: true
simple_preauth:
authenticator: app.authenticator
access_control:
- { path: ^/admin, roles: IS_AUTHENTICATED_ANONYMOUSLY }
Here's my authenticator i'm testing this out with:
<?php
class ApiKeyAuthenticator implements SimplePreAuthenticatorInterface, AuthenticationFailureHandlerInterface
{
/**
* {@inheritdoc}
*/
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
{
$apiKey = $token->getCredentials();
$user = $userProvider->loadUserByUsername("foobar");
return new PreAuthenticatedToken(
$user,
$apiKey,
$providerKey,
$user->getRoles()
);
}
/**
* {@inheritdoc}
*/
public function supportsToken(TokenInterface $token, $providerKey)
{
return $token instanceof PreAuthenticatedToken && $token->getProviderKey() === $providerKey;
}
/**
* {@inheritdoc}
*/
public function createToken(Request $request, $providerKey)
{
$apiKey = $request->headers->get('Authorization');
if (!$apiKey) {
return;
}
return new PreAuthenticatedToken(
'anon.',
$apiKey,
$providerKey
);
}
/**
* {@inheritdoc}
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
return new JsonResponse(['errors' => ["Authentication Failed."]], Response::HTTP_FORBIDDEN);
}
}