poetic / apollo-datasource-graphql

GraphQL/Apollo DataSource to connect to GraphQL API's from your Apollo Server
84 stars 18 forks source link

Unable to set an authentication bearer token in willSendRequest #14

Open patricksimonian opened 5 years ago

patricksimonian commented 5 years ago

I'm trying to leverage the Github v4 graphql api as a data source and as per the instructions, I modified the request object with an authorization header.

I receive 401 errors performing any queries against my apollo server. I can confirm I have a valid auth token as I am independently able to perform the query with curl

 willSendRequest(request) {
    console.log('THE REQUEST', request);
    if (!request.headers) {
      request.headers = {};
    }

    request.headers.authorization = `Bearer ${this.authToken}`;
  }
klict commented 4 years ago

If the implementation is the same as apollo-rest-data-source then this should work:

willSendRequest(request) {
    request.headers.set('authorization',`Bearer ${this.authToken}`);
  }
RobertDGordon commented 4 years ago

The implementation of apollo-datasource-graphql is not the same as apollo-datasource-rest as there is no access to the set() method.

Here is what our team was able to get working for apollo-datasource-graphql. (Note, the console log at the end of willSendRequest to ensure your header is set correctly.)

class GitHubAPI extends GraphQLDataSource{
        baseURL = 'https://api.github.com/graphql';
        token = 'bearer 1010101010101010101010101';

    willSendRequest(request) {
        if(!request.headers) {
            request.headers = {};
        }

        request.headers.Authorization = `${this.token}`;
        console.log(request);
    }
...
timesync commented 4 years ago

This definitely needs to be in the documentation somewhere.

darrenbarklie commented 3 years ago

Thanks for the pointers above. For another use case, I configured a Braintree Payments as:

class BraintreeGraphQLAPI extends GraphQLDataSource {
  baseURL = "https://payments.sandbox.braintree-api.com/graphql";

  willSendRequest(request) {
    if (!request.headers) {
      request.headers = {};
    }
    request.headers = {
      Authorization: `Basic ${process.env.BRAINTREE_API_KEY}`,
      "Content-Type": "application/json",
      "Braintree-Version": "2021-03-14",
    };
  }

  async pingBraintreeService() {
    try {
      const response = await this.query(PING_BRAINTREE_SERVICE);

      return response.data.ping;
    } catch (error) {
      console.error(error);
    }
  }
}