Question:
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.
So far I have followed the header authentication documentation here: https://www.apollographql.com/docs/react/recipes/authentication.html
And have this code, which I adapted to include the token call to the Amplify authentication service but it returns a 401 error:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
const httpLink = createHttpLink({ uri: '[API end point address]/graphql' }); const authLink = setContext((_, { headers }) => { const token = async () => (await Auth.currentSession()).getAccessToken().getJwtToken(); return { headers: { ...headers, authorization: token ? `Bearer ${token}` : "" } } }) const client = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache() }) |
The only documentation I can find relating to this doesn’t provide any technical instructions:
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.
From here: https://docs.aws.amazon.com/appsync/latest/devguide/security.html
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?
Edit:
So far i have tried changing this line:
1 2 |
authorization: token ? `Bearer ${token}` : "" |
The following attempts:
1 2 3 4 5 6 7 8 |
token jwtToken: token authorization: token Authorization: token |
None of these have worked either.
Answer:
Disclaimer: Never tried it, but here is what I would do:
Check out the AppSync Client code here as a foundation for creating a an Authentication link for Apollo Client and the AppSync server. It looks like that code provides the scaffolding for each of the available authentication methods.
Specifically, if you are trying to use the OPENID_CONNECT method of authentication, it appears as if the JWT token does not need to be prepended by Bearer
(line 156).