How to pass Authorization Header to GraphQL using Amplify in React Native

Viewed 1384

All,

We are using React Native to develop a mobile application, We are using APP Sync for few operations.

Earlier we use API_KEY for authorization and the graphql code is straight forward. We configure the all the required keys and directly do the query in

API.graphql( graphqlOperation(updatedata, { id, record }) )

Now we have change in the Authorization type, moved from API Key to access token from cognito from server due to some security changes. We get the accesstoken for Authorization, Now how can we send the Authorization token for every Graphql request or How to handle it?

Can anyone explain

1 Answers

According to the README for the amplify-js library, you have two options:

  1. You can use the built-in Amplify Auth functions if they're appropriate:
// For React Native
import { withAuthenticator } from 'aws-amplify-react-native';

// Will provide customizable UI for your user to authenticate
export default withAuthenticator(App);
  1. Otherwise, you can add a header on your own:
import API from '@aws-amplify/api';
let token = '/* Your API Token */';
let apiName = 'MyApiName';
let path = '/path';
let options = {
  headers: {
    Authorization: `bearer ${token}`
  } // OPTIONAL
}

API.get(apiName, path, options).then(response => {
  // Add your code here
});

Both of these samples are pulled directly from the readme linked at the top of this answer, so I'd recommend checking it out for further info.

Related