/** * @ApiDoc( * resource=true, * description="Create new user", * section="User", * statusCodes={ * 201="User created", * 400="Incorrect 'name' provided" * } * ) * @RequestParam(name="name", requirements=".*\S.*", allowBlank=false) * * @param ParamFetcher $paramFetcher * @return Response */ public function postUserAction(ParamFetcher $paramFetcher) { $user = new User(); $user->setName($paramFetcher->get('name')); $this->entityManager->persist($user); $this->entityManager->flush(); $apiKey = $this->apiKeyManager->generateApiKeyForUser($user); $view = $this->routeRedirectView('api_v1_get_user', ['requestedUser' => $user->getId()])->setHeader(Headers::API_KEY, $apiKey); return $this->handleView($view); }
/** * @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'); }