Search code examples
javascriptgithub-apifetch-api

Client secret & id to be deprecated in the coming months


My code works but the request format will be deprecated in the coming months.

New format suggested from Github

curl -u my_client_id:my_client_secret https://api.github.com/users/user

Can someone show me the correct way to reformat it for when it is deprecated in the coming months. I've tried everything. Here is one example of what I've tried:

My attempt that doesn't work

`-u ${this.client_id}:${this.client_secret} https://api.github.com/users/${user}`

My current code

class Github {
  constructor() {
    // THESE ARE FAKE!!!
    this.client_id = 'a71344259aec03d0cea3';
    this.client_secret = 'a28202377336e199cb554bd099e6e5fe672788db';
    this.repos_count = 7;
    this.repos_sort = 'created: asc';
  }

  async getUser(user) {
    const profileResponse = await fetch(
      `https://api.github.com/users/${user}?client_id=${this.client_id}&client_secret=${this.client_secret}`
    );

    const repoResponse = await fetch(
      `https://api.github.com/users/${user}/repos?per_page=${this.repos_count}&sort=${this.repos_sort}&client_id=${this.client_id}&client_secret=${this.client_secret}`
    );
    console.log(user);

    const profile = await profileResponse.json();
    const repos = await repoResponse.json();

    return {
      profile,
      repos,
    };
  }
}

Solution

  • The -u option in curl uses HTTP Basic authentication.

    What this does is takes the user:password string, base64-encodes it (eg user:password => dXNlcjpwYXNzd29yZA==) and adds it to the Authorization request header like this

    Authorization: Basic dXNlcjpwYXNzd29yZA==
    

    When using fetch, you have to do this manually using something like btoa()

    const auth = btoa(`${this.client_id}:${this.client_secret}`)
    
    fetch(`https://api.github.com/users/${encodeURIComponent(user)}`, {
      headers: {
        Authorization: `Basic ${auth}`
      }
    })