使用纯Javascript或JQuery的Google OAuth 2访问令牌

我正在测试Google OAuth 2.0。我有我的客户ID,客户密码和验证码。现在,我想获取访问权限并刷新令牌。

但是,我可以从PHP做到这一点。但是在使用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>

基本上,我正在尝试将以下PHP Curl POST请求转换为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);

注意:堆栈溢出中类似类型的问题有很多视图,但仍未得到解答。天才的开发人员请提供您的意见。我也被困了三天。

js333888 回答:使用纯Javascript或JQuery的Google OAuth 2访问令牌

感谢@Tankaike。在StackOverflow中,此问题被询问了3-4次,没有人认真回答。

初学者!!!需要注意的一点是:身份验证代码只能使用一次 :)要获取新的访问令牌,请使用您从第一个响应中获得的刷新令牌

        $.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);
            }
        });
本文链接:https://www.f2er.com/3131428.html

大家都在问