title: Authenticate Apollo GraphQL API with Passport Facebook
body: <p>I have a client server and an API, both using <a href="http://dev.apollodata.com/" rel="noreferrer">Apollo</a>. When the user logs in with Facebook I want to send a token to my client server which will then be appended to the headers of every request made to the API. Without using sessions.</p>
  
  <p>Here's how the API looks, this generates the token successfully when a user logs in with Facebook (I'm also checking for users in a database behind the scenes).</p>
  
  <pre><code>// API running on port 3010
  app.use(expressJwt({
      secret: authConfig.jwt.secret,
      credentialsRequired: false,
      getToken: req =&gt; req.cookies.id_token,
  }));
  app.use(passport.initialize());
  app.get('/login/facebook',
      passport.authenticate('facebook', { scope: ['email'], session: false }),
  );
  
  app.get('/login/facebook/return',
      passport.authenticate('facebook', { failureRedirect: 'http://localhost:3000/login', session: false }),
      (req, res) =&gt; {
          const expiresIn = 60 * 60 * 24 * 1; // 1 day
          const token = jwt.sign(req.user, authConfig.jwt.secret, { expiresIn });
          res.redirect(`http://localhost:3000?token=${token}`); // Redirect to client and append token to param
      },
  );
  </code></pre>
  
  <p>My question is, how do I now hand this token to the client securely? I've read <a href="http://dev.apollodata.com/react/auth.html#Header" rel="noreferrer">this</a> and <a href="http://pcarion.com/2015/10/18/graphql-and-json-web-token/" rel="noreferrer">this</a>, which led me to passing the token in a param, but I'm not sure if what I'm doing is secure.</p>
  
  <p>Here's how I'm getting it on the client side:</p>
  
  <pre><code>const token = getURLParameterByName('token');
  if (token) {
      localStorage.setItem('token', token);
  }
  
  networkInterface.use([{
      applyMiddleware(req, next) {
          if (!req.options.headers) {
              req.options.headers = {};   // Create the header object if needed.
          }
  
          // Get the authentication token from local storage if it exists
          const localToken = localStorage.getItem('token')
          req.options.headers.authorization = localToken ? `Bearer ${localToken}` : null;
          next();
      },
  }]);
  </code></pre>
  
  <p>After this, using it in the API:</p>
  
  <pre><code>app.use('/graphql', apolloExpress(req =&gt; {
      let token;
      if (req.headers.authorization) {
          token = req.headers.authorization;
          console.log(token);
      }
  
      return {
          schema: executableSchema,
          context: {
              token,
          },
      };
  }));
  </code></pre>