javascript 中的 Twitter OAuth 身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6700106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:34:57  来源:igfitidea点击:

Twitter OAuth authentication in javascript

javascriptjqueryajaxtwitteroauth

提问by Deylo Woo

I have looked everywhere for a good example of a JQuery ajax call to authenticate a use in Twitter using their OAuth method. I read the instructions several times and this is what I have so far, at the moment I am only trying to get the Oauth_Token to send the user to validate. I keep getting the error 401 unauthorized error. I have tried a few combinations changing the dataType and couple other things in the ajax call but no success. I believe that the "Create base signature and the Create signature from SHA1 encryption" is correct, but I could be wrong. If anyone has implement twitter OAuth in javascript successfully please let me know how. I am also not interested in using a third party API, I actually want to learn this. Thanks in advance for any help.

我到处寻找 JQuery ajax 调用的一个很好的例子,以使用他们的 OAuth 方法来验证 Twitter 中的使用。我多次阅读说明,这就是我目前所拥有的,目前我只是试图让 Oauth_Token 发送用户进行验证。我不断收到错误 401 未经授权的错误。我尝试了一些组合更改数据类型和 ajax 调用中的其他一些东西,但没有成功。我相信“从 SHA1 加密创建基本签名和创建签名”是正确的,但我可能是错的。如果有人在 javascript 中成功实现了 twitter OAuth,请告诉我如何。我也对使用第三方 API 不感兴趣,我实际上想学习这个。在此先感谢您的帮助。

Twitter instructions http://dev.twitter.com/pages/auth

Twitter 说明http://dev.twitter.com/pages/auth

My code (Javascript)

我的代码(Javascript)

    //Unix time
    var foo = new Date; // Generic JS date object
    var unixtime_ms = foo.getTime(); // Returns milliseconds since the epoch
    var unixtime = parseInt(unixtime_ms / 1000);

    var callBackURL = "oob"; //oob for now
    var nonce = "12342897";

    //Create Signature Base String using formula
    var baseSign = "POST" + "&" + encodeURIComponent("https://api.twitter.com/oauth/request_token").toString() + "&"
     + encodeURIComponent("oauth_callback") + "%3D" + encodeURIComponent(callBackURL)
     + "%26"
     + encodeURIComponent("oauth_consumer_key") + "%3D" + encodeURIComponent("*****consumer key**********")
     + "%26"
     + encodeURIComponent("oauth_nonce") + "%3D" + encodeURIComponent(nonce)
     + "%26"
     + encodeURIComponent("oauth_signature_method") + "%3D" + encodeURIComponent("HMAC-SHA1")
     + "%26"
     + encodeURIComponent("oauth_timestamp") + "%3D" + encodeURIComponent(unixtime)
     + "%26"
     + encodeURIComponent("oauth_version") + "%3D" + encodeURIComponent("1.0");

    //Create Signature, With consumer Secret key we sign the signature base string
    var signature = b64_hmac_sha1("********secrete key****************", baseSign);

    //Build headers from signature
    var jsonData = JSON.stringify({
        Authorization: {
            oauth_nonce: nonce,
            oauth_callback: encodeURIComponent(callBackURL),
            oauth_signature_method: "HMAC-SHA1",
            oauth_timestamp: unixtime,
            oauth_consumer_key: "**********consumer key*********",
            oauth_signature: signature,
            oauth_version: "1.0"
        }
    });

    //Request Access Token
    $.ajax({
        url: "http://api.twitter.com/oauth/request_token",
        type: "post",
        headers: jsonData,
        dataType: "jsonp",
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            alert("Error");
        }

Here is the HTTP response

这是 HTTP 响应

HTTP/1.1 401 Unauthorized
Date: Thu, 14 Jul 2011 21:05:55 GMT
Server: hi
Status: 401 Unauthorized
X-Transaction: 1310677555-60750-49846
X-Frame-Options: SAMEORIGIN
Last-Modified: Thu, 14 Jul 2011 21:05:55 GMT
X-Runtime: 0.01152
Content-Type: text/html; charset=utf-8
Pragma: no-cache
X-Revision: DEV
Expires: Tue, 31 Mar 1981 05:00:00 GMT
X-MID: ffc990286a86b688f1e72ef733365926ea30ca62
Vary: Accept-Encoding
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0, proxy-revalidate
Content-Length: 44
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Set-Cookie: lang=en; path=/
Set-Cookie: lang=en; path=/
Set-Cookie: _twitter_sess=BAh7DjoOcmV0dXJuX3RvIiJodHRwOi8vdHdpdHRlci5jb20vcGF1bF9pcmlz%250AaDoJdXNlcmkEl6phBDoVaW5fbmV3X3VzZXJfZmxvdzA6D2NyZWF0ZWRfYXRs%250AKwgE9BTnMAE6B2lkIiU2MzBkYmJmNmY4YmRmY2E3NGI2NDRmZTFhNjZiNmU2%250ANToTc2hvd19oZWxwX2xpbmswOgxjc3JmX2lkIiUyODIzYWNlNmFjMzQ3OTk5%250AZDE5YmVlYmJlYzM4MTg0ZSIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6%250ARmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7ADoTcGFzc3dvcmRfdG9rZW4i%250ALThkY2NlMmE1OTI5OWJmM2VjNDI4YWRiOTE0YTRmYzVjYzQwN2FkMmM%253D--22a361f562df3aa6991b81fff6f486086ab71f0e; 
domain=.twitter.com; 
path=/; HttpOnly
Proxy-support: Session-based-authentication
Age: 0

Failed to validate oauth signature and token

回答by arthurfonseca

I had exactly the same issue. After lose a few hours at the twitter developers page i found this:

我有完全相同的问题。在 Twitter 开发人员页面上失去了几个小时后,我发现了这一点:

https://dev.twitter.com/discussions/3454

https://dev.twitter.com/discussions/3454

Basicly you can't get the oauth_token this way on the client side. That's why you are always getting error 401.

基本上,您无法在客户端以这种方式获取 oauth_token。这就是为什么您总是收到错误 401 的原因。

There's a solution to avoid server side using the 'xauth' (https://dev.twitter.com/docs/oauth/xauth), but to do so you need to send a detailed message to [email protected] to request xAuth privileges.

有一个解决方案可以避免服务器端使用“xauth”(https://dev.twitter.com/docs/oauth/xauth),但要这样做,您需要向 [email protected] 发送详细消息以请求 xAuth特权。

回答by Marco Bettiolo

The purpose of the 3-leggedo OAuth is to get the user authorise your application's access to the his data. You cannot issue programmatically a Request Token and the an Access Token. The Request Token must be authorised by the user via his browser on a different flow before you can exchange it and get an Access Token.

3-leggedo OAuth 的目的是让用户授权您的应用程序访问他的数据。您不能以编程方式发出请求令牌和访问令牌。请求令牌必须由用户通过他的浏览器在不同的流程上授权,然后您才能交换它并获得访问令牌。