javascriptajaxgoogle-apigoogle-oauthgoogle-api-client

Google OAuth 2 Access Token using pure Javascript or JQuery


I am testing Google OAuth 2.0. I have my Client ID, Client Secret and Auth Code. Now I want to get an access and refresh token.

However, I am able to do that from PHP. But getting Invalid Grant error while using Javascript.

    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
    </head>

    <body>
        <a href='#' onClick='getAccessToken();'> Get your Access Token </a>
        <pre id="response"> </pre>

        <script>
            function getAccessToken() {

                $.ajax({
                    type: 'POST',
                    url: "https://accounts.google.com/o/oauth2/token",
                    contentType: 'application/x-www-form-urlencoded',
                    dataType: 'json',
                    data: {
                        client_id: 'MY CLIENT ID',
                        client_secret: 'MY SECRET',
                        code: 'MY AUTH CODE',
                        redirect_uri: 'http://localhost:8888/google-api.html',
                        grant_type: 'authorization_code'
                    },

                    success: function (data) {
                        $('#response').html(data);
                    },
                    error: function (e) {
                        $('#response').html(e.responseText);
                    }
                });

            }
        </script>

    </body>
    </html>

Basically I am trying to convert the below PHP Curl POST request to Ajax

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"https://accounts.google.com/o/oauth2/token");
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/x-www-form-urlencoded']);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'code'          => $code,
        'client_id'     => $client_id,
        'client_secret' => $client_secret,
        'redirect_uri'  => $redirect_uri,
        'grant_type'    => 'authorization_code',
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close ($ch);

Note: Similar type of questions in stack overflow have many views but yet remained unanswered. The genius developers kindly give your input. I am also stuck since 3 days.


Solution

  • Thanks to @Tankaike. This question was asked 3-4 times in StackOverflow and no one replied it carefully.

    Beginners!!! One point to be noted: Auth Code works only once :) To get a new access token use refresh token that you have got from the first response

            $.ajax({
                type: 'POST',
                url: "https://accounts.google.com/o/oauth2/token",
                contentType: 'application/x-www-form-urlencoded; charset=utf-8',
                crossDomain:true,
                cache : true, 
                dataType: 'json',
                data: {
                    client_id: client_id,
                    client_secret: client_secret,
                    code: code,
                    redirect_uri: redirect_uri,
                    grant_type: grant_type,
                },
    
                success: function (data) {
                    $('#response').html(JSON.stringify(data, null, " "));;
                },
                error: function (e) {
                    $('#response').html(e.responseText);
                }
            });