title: Authenticate Apollo Client to AWS AppSync with Cognito User Pools
body: <p>I am trying to connect to my AWS AppSync API using the plain Apollo Client but I am not sure how to structure the authentication header correctly. </p>
  
  <p>So far I have followed the header authentication documentation here: <a href="https://www.apollographql.com/docs/react/recipes/authentication.html" rel="noreferrer">https://www.apollographql.com/docs/react/recipes/authentication.html</a></p>
  
  <p>And have this code, which I adapted to include the token call to the Amplify authentication service but it returns a 401 error:</p>
  
  <pre><code>const httpLink = createHttpLink({
    uri: '[API end point address]/graphql'
  });
  
  const authLink = setContext((_, { headers }) =&gt; {
    const token = async () =&gt; (await Auth.currentSession()).getAccessToken().getJwtToken();
    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : ""
      }
    }
  })
  
  const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache()
  })
  </code></pre>
  
  <p>The only documentation I can find relating to this doesn't provide any technical instructions: </p>
  
  <blockquote>
    <p>When using Amazon Cognito User Pools, you can create groups that users
    belong to. This information is encoded in a JWT token that your
    application sends to AWS AppSync in an authorization header when
    sending GraphQL operations.</p>
  </blockquote>
  
  <p>From here: <a href="https://docs.aws.amazon.com/appsync/latest/devguide/security.html" rel="noreferrer">https://docs.aws.amazon.com/appsync/latest/devguide/security.html</a></p>
  
  <p>I know that token is fine because if I use the AppSync JavaScript API then it works. Is there anywhere I can go to find out how to achieve this or does someone know how? </p>
  
  <p>Edit: </p>
  
  <p>So far i have tried changing this line:</p>
  
  <pre><code>  authorization: token ? `Bearer ${token}` : ""
  </code></pre>
  
  <p>The following attempts: </p>
  
  <pre><code>token
  
  jwtToken: token
  
  authorization: token
  
  Authorization: token
  </code></pre>
  
  <p>None of these have worked either.</p>