Wednesday, 30 September 2020

How to use AMAZON_COGNITO_USER_POOLS with apollo-client

I am trying to populate my jwtToken with the newer @aws-amplify packages and it is proving somewhat difficult.

When trying to run a Query I will get the following error: Uncaught (in promise) No current user

I can see from the source that if I have auth type set to AMAZON_COGNITO_USER_POOLS then I have to use a jwt token

        case AUTH_TYPE.AMAZON_COGNITO_USER_POOLS:
        case AUTH_TYPE.OPENID_CONNECT:
            const { jwtToken = '' } = auth;
            promise = headerBasedAuth({ header: 'Authorization', value: jwtToken }, operation, forward);

So this leads me to trying to generate my JWT token and this is where my knowledge fails me. I know that jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken(), returns a promise as is required as seen in the above code... So I cannot see why this would fail?

_app.js (next.js)

import Amplify from '@aws-amplify/core'
import { Auth } from '@aws-amplify/auth'
import { ApolloProvider } from '@apollo/react-hooks'
import { ApolloLink } from 'apollo-link'
import { createAuthLink } from 'aws-appsync-auth-link'
import { InMemoryCache, ApolloClient } from '@apollo/client'
import { createHttpLink } from 'apollo-link-http'

import awsExports from '../aws-exports'

Amplify.configure(awsExports)
Auth.configure(awsExports)

const url = awsExports.aws_appsync_graphqlEndpoint
const region = awsExports.aws_appsync_region

const auth = {
  type: awsExports.aws_appsync_authenticationType,
  jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken(),
}
const link = ApolloLink.from([createAuthLink({ url, region, auth }), createHttpLink({ uri: url })])
const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
})

const MyApp = function ({ Component, pageProps, router }) {
  return (
        .....
          <ApolloProvider client={client}>
        .....
  )
}

export default MyApp


from How to use AMAZON_COGNITO_USER_POOLS with apollo-client

No comments:

Post a Comment