Search code examples
githuboauth-2.0graphql

GraphQL query to GitHub failing with HTTP 422 Unprocessable Entity


I am currently working on a simple GitHub GraphQL client in NodeJS.

Given that GitHub GraphQL API is accessible only with an access token, I set up an OAuth2 request to grab the access token and then tried to fire a simple GraphQL query.

OAuth2 flow gives me the token, but when I send the query, I get HTTP 422.

Here below simplified snippets from my own code:

  1. Prepare the URL to display on UI side, to let user click it and perform login with GitHub
getGitHubAuthenticationURL(): string {
  const searchParams = new URLSearchParams({
    client_id,
    state,
    login,
    scope,
  });
  return `https://github.com/login/oauth/authorize?${searchParams}`;
}
  1. My ExpressJs server listening to GitHub OAuth2 responses
httpServer.get("/from-github/oauth-callback", async (req, res) => {
  const {
    query: { code, state },
  } = req;
  const accessToken = await requestGitHubAccessToken(code as string);
  
  [...]
});
  1. Requesting access token
async requestToken(code: string): Promise<string> {
  const { data } = await axios.post(
    "https://github.com/login/oauth/access_token",
    {
      client_id,
      client_secret,
      code
    },
    {
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    }
  );
  return data.access_token;
}
  1. Firing simple graphql query
const data = await axios.post(
  "https://graphql.github.com/graphql/proxy",
  { query: "{ viewer { login } }"},
  {
    headers: {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json",
    },
  }
);

Do you guys have any clue? Perhaps I am doing something wrong with the OAuth2 flow? As in most of the examples I found on the web, a personal token is used for this purpose, generated on GitHub, but I would like to use OAuth2 instead.

Thanks in advance for any help, I really appreciate it!

EDIT I changed the query from { query: "query { viewer { login } }"} to { query: "{ viewer { login } }"}, nonetheless, the issue is still present.


Solution

  • I finally found the solution:

    1. Change the URL from https://graphql.github.com/graphql/proxy to https://api.github.com/graphql, see here
    2. Add the following HTTP headers
    • "Content-Type": "application/json"
    • "Content-Length"
    • "User-Agent"

    Hope this will help others out there.