/** * @inheritdoc */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { if (!$userProvider instanceof ApiKeyUserProvider) { throw new \InvalidArgumentException(sprintf('The user provider must be an instance of ApiKeyUserProvider (%s was given).', get_class($userProvider))); } $apiKey = $token->getCredentials(); try { $apiKeyInfo = $this->apiKeyManager->getInfoFromApiKey($apiKey); } catch (\Exception $e) { $this->logger->error('Someone is trying to fake the token', [$this->serverBag]); throw new InvalidApiKeyException($apiKey, 0, $e); } $user = $userProvider->loadUserById($apiKeyInfo->id); if ($apiKeyInfo->token !== $user->getToken()) { $this->logger->alert('Someone found the JWT secret and is trying to fake the token', [$this->serverBag]); throw new InvalidApiKeyException($apiKey); } return new PreAuthenticatedToken($user, $apiKey, $providerKey, $user->getRoles()); }
/** * @expectedException \AppBundle\Exception\InvalidApiKeyException * @expectedExceptionMessage API key `apiKey` is invalid */ public function testAuthenticateTokenThrowsExceptionForFakeToken() { $userProvider = $this->prophesize('AppBundle\\Security\\ApiKeyUserProvider'); $token = $this->prophesize('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface'); $user = $this->prophesize('AppBundle\\Entity\\User'); $token->getCredentials()->willReturn('apiKey'); $apiKeyInfo = new \stdClass(); $apiKeyInfo->id = 1; $apiKeyInfo->token = 'userToken1'; $this->apiKeyManager->getInfoFromApiKey('apiKey')->willReturn($apiKeyInfo); $userProvider->loadUserById(1)->willReturn($user); $user->getToken()->willReturn('userToken2'); $this->logger->alert(Argument::cetera())->shouldBeCalled(); $this->apiKeyAuthenticator->authenticateToken($token->reveal(), $userProvider->reveal(), 'key'); }
/** * @expectedException \AppBundle\Exception\InvalidApiKeyException * @expectedExceptionMessage API key `apiKey` is invalid */ public function testGetInfoFromApiKeyThrowsExceptionForInvalidApiKey() { $this->apiKeyManager->getInfoFromApiKey('apiKey'); }