Search code examples
javascriptnode.jsgithubgithub-api

Find out username after user has logged in to GitHub via oAuth2


We are building a project where a client logs into Github via a redirect link from our landing page and we receive a code which we swap for a token. However, we want to make a request to the Github API with that particular user's Github username (to retrieve their closed issues).

We've logged the request object, the response object and the headers and the username isn't there. The username must be located somewhere but we can't find it. If anyone has experience retrieving the username with external authorisation we'd be grateful for your help.


Solution

  • You can perform a get request to the github API, to the path

    /user?access_token=ACCESS_TOKEN
    

    Where ACCESS_TOKEN is the access token for the user you want the details of.

    The response defaults as a JSON object which has a key 'login' whose value is the user's username.

    In Node.js you can perform a get request with the following options:

    var options = {
      host: 'api.github.com',
      path: '/user?access_token=' + accessToken,
      headers: {
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36'
      }
    };
    

    A user-agent string in the header is necessary for github requests.

    See this link for more information, and a sample response from that endpoint.

    https://developer.github.com/v3/users/#get-a-single-user