title: Symfony3: A Token was not found in the TokenStorage : AuthenticationCredentialsNotFoundException
body: <p>I followed the Symfony doc. tutorial <a href="https://symfony.com/doc/current/security/api_key_authentication.html" rel="nofollow noreferrer">here</a> and developed the API key authentication mechanism in my application.
  My <code>security.yml</code> looks like follows and I need the chain provider to fallback to http basic auth in case the user is not found with the API key.</p>
  
  <pre><code>security:
      encoders:
          FOS\UserBundle\Model\UserInterface: sha512
          Symfony\Component\Security\Core\User\User:
              algorithm: bcrypt
              encode_as_base64: false
              iterations: 4
  
  role_hierarchy:
      ROLE_ADMIN:       ROLE_USER
      ROLE_SUPER_ADMIN: ROLE_ADMIN
  
  providers:
      api_key_user_provider:
          id: AppBundle\Security\ApiKeyUserProvider
      fos_userbundle:
          id: fos_user.user_provider.username
      chain_provider:
          chain:
              providers: [api_key_user_provider, fos_userbundle]
  
  firewalls:
      dev:
          pattern: ^/(_(profiler|wdt)|css|images|js)/
          security: false
  
      user:
          pattern: ^/users/
          anonymous: true
          stateless: true
          logout: true
  
      api:
          anonymous: false
          stateless: true
          simple_preauth:
              authenticator: AppBundle\Security\ApiKeyAuthenticator
          provider: chain_provider
  </code></pre>
  
  <p>When I try to access secured area ('api') of the system, it throws the above error. I am quiet new to Symfony firewall config, and could anyone please show me the correct direction on this?</p>
  
  <p>My <code>ApiKeyUserProvider</code> class looks like follows:</p>
  
  <pre><code>class ApiKeyUserProvider implements UserProviderInterface
  {
      /** @var EntityManager $entityManager */
      protected $entityManager;
  
      public function __construct(EntityManager $entityManager)
      {
          $this-&gt;entityManager = $entityManager;
      }
  
      /**
       * Get the username of a user for a given API key
       *
       * @param $apiKey
       * @return string|null
       */
      public function getUsernameForApiKey($apiKey)
      {
          $apiKeyRepository = $this-&gt;entityManager-&gt;getRepository('UserBundle:ApiKey');
  
          $username = $apiKeyRepository-&gt;getUserNameForApiKey($apiKey);
  
          return $username;
      }
  
      /**
       * Loads the user for the given username.
       *
       * This method must throw UsernameNotFoundException if the user is not
       * found.
       *
       * @param string $username The username
       *
       * @return UserInterface
       *
       * @throws UsernameNotFoundException if the user is not found
       */
      public function loadUserByUsername($username)
      {
          $userRepository = $this-&gt;entityManager-&gt;getRepository('UserBundle:User');
  
          $user = $userRepository-&gt;findOneByUsername($username);
  
          if (!$user instanceof User) {
  
              throw new UsernameNotFoundException();
          }
  
          return $user;
      }
  
      /**
       * Refreshes the user.
       *
       * It is up to the implementation to decide if the user data should be
       * totally reloaded (e.g. from the database), or if the UserInterface
       * object can just be merged into some internal array of users / identity
       * map.
       *
       * @return UserInterface
       *
       * @throws UnsupportedUserException if the user is not supported
       */
      public function refreshUser(UserInterface $user)
      {
          // this is used for storing authentication in the session
          // but in this case, the token is sent in each request,
          // so authentication can be stateless. Throwing this exception
          // is proper to make things stateless
          throw new UnsupportedUserException();
      }
  
      /**
       * Whether this provider supports the given user class.
       *
       * @param string $class
       *
       * @return bool
       */
      public function supportsClass($class)
      {
          return User::class === $class;
      }
  }
  </code></pre>
  
  <p>And my <code>ApiKeyAuthenticator</code> class looks like as follows:</p>
  
  <pre><code>class ApiKeyAuthenticator implements SimplePreAuthenticatorInterface
  {
      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-&gt;getCredentials();
          $username = $userProvider-&gt;getUsernameForApiKey($apiKey);
  
          if (!$username) {
              // CAUTION: this message will be returned to the client
              // (so don't put any un-trusted messages / error strings here)
              throw new CustomUserMessageAuthenticationException(
                  sprintf('API Key "%s" does not exist.', $apiKey)
              );
          }
  
          $user = $userProvider-&gt;loadUserByUsername($username);
  
          return new PreAuthenticatedToken(
              $user,
              $apiKey,
              $providerKey,
              $user-&gt;getRoles()
          );
      }
  
      public function supportsToken(TokenInterface $token, $providerKey)
      {
          return $token instanceof PreAuthenticatedToken &amp;&amp; $token-&gt;getProviderKey() === $providerKey;
      }
  
      public function createToken(Request $request, $providerKey)
      {
          // look for an apikey query parameter
  //        $apiKey = $request-&gt;query-&gt;get('apikey');
  
          // or if you want to use an "apikey" header, then do something like this:
          $apiKey = $request-&gt;headers-&gt;get('apikey');
          if (!$apiKey) {
              // throw new BadCredentialsException();
  
              // or to just skip api key authentication
              return null;
          }
  
          return new PreAuthenticatedToken(
              'anon.',
              $apiKey,
              $providerKey
          );
      }
  }
  </code></pre>