how to get the github oauth access_token

203 Views Asked by At

Lately Github updated the Oauth apis and documentation. I am unable to get the access_token from this api

POST https://github.com/login/oauth/access_token ( I am always receving CORS error in production server)

I have tried both post calls passing correct client_id, client_secret and the code as url param as well as as payload

I have no problem receiving code from the /authorize endpoint and I am using this code in above as described in the documentation. https://github.com/login/oauth/authorize?client_id=${environment.client_id}

2

There are 2 best solutions below

2
user229044 On

POST https://github.com/login/oauth/access_token ( I am always receving CORS error in production server)

Then you're doing the POST from a browser, which is a serious error. You cannot do that. The POST happens from your server, to Github's server. As it stands, you're exposing your client_secret to the browser which is a serious security problem.

0
user2746732 On

Here is my php proxy and it is working (it took my life ! github documentation was not that friendlier for me) thanks @user229044 for giving me the pointer that I need to have my server to request the token

<?php
        include('ghconfig.php');


  $url = "https://github.com/login/oauth/access_token";

  $params = array(
    'client_id' => $client_id,
    'client_secret' => $client_secret,
    'code' => $_GET["code"]
  );
  $postdata = "client_id=".$client_id."&client_secret=".$client_secret."&code=".$_GET["code"];

  $options = [
    'http' => [
        'header' => "Accept:application/json",
        'method' => 'POST',
        'content' => $postdata,
],
];

  $context = stream_context_create($options);
  $result = file_get_contents($url, false, $context);
  if ($result === false) {
    die("Url: " .$url ."  payload : ".$postdata);
  }

  echo $result;
?>