I'm writing a bundle for Symfony2 and I need to write a custom authentication system with guards. The whole system is based on tokens. Let's assume I need to send a POST request. In headers I have to include 'TOKEN: testtoken'.
-
I send a request without 'TOKEN: testtoken' in headers and I get
{ "message": "Authentication Required" }
-
I send a request with 'TOKEN: badtoken' and I get
{ "message": "Username could not be found." }
Don't look at 'username'. It's mistake.
-
I send request with 'TOKEN: testtoken' and I get
{ "token": "testtoken" }
It's just example page.
-
Now I delete 'TOKEN: testtoken' from headers (I use Postman for testing REST APIs) and I get
{ "token": "testtoken" }
I have no idea why. In my opinion in this case my system should return
{ "message": "Authentication Required" }
Here’s my TokenAuthenticator.php
<?php
namespace WLN\AuthTokenBundle\Security;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
class TokenAuthenticator extends AbstractGuardAuthenticator
{
private $em;
private $user_repository;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function setConfig($user_repo)
{
$this->user_repository = $user_repo;
}
public function getCredentials(Request $request)
{
if($token = $request->headers->get('WLN-AUTH-TOKEN'))
{
return [
'token' => $token
];
}
return null;
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$token = $credentials['token'];
return $this->em->getRepository($this->user_repository)
->findOneBy(array('token' => $token));
}
public function checkCredentials($credentials, UserInterface $user)
{
return true;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = array(
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
);
return new JsonResponse($data, 403);
}
public function start(Request $request, AuthenticationException $authException = null)
{
$data = array(
'message' => 'Authentication Required'
);
return new JsonResponse($data, 401);
}
public function supportsRememberMe()
{
return false;
}
}
P.S. My app is on shared-hosting. May caching cause it or something like that?