当前位置: 首页 > 知识库问答 >
问题:

401无法验证oauth签名和令牌(https://api.twitter.com/oauth/request_token)(Java代码)

齐凯康
2023-03-14

我试图从twitter api获取oauth\u令牌,但出现异常:
java。io。IOException:服务器返回了URL的HTTP响应代码:401:https://api.twitter.com/oauth/request_token

错误流获取:
验证oauth签名和令牌失败

以下是SignatureBasString、签名和授权标头示例:
SignatureBasString:POST

下面是一个代码:
名称值对比较器:

class NvpComparator implements Comparator<NameValuePair> {
        @Override
        public int compare(NameValuePair arg0, NameValuePair arg1) {
            String name0 = arg0.getName();
            String name1 = arg1.getName();
            return name0.compareTo(name1);
        }
    }

URL编码

class OAuth{
...
    public static String percentEncode(String s) {
            return URLEncoder.encode(s, "UTF-8")
                    .replace("+", "%20").replace("*", "%2A")
                    .replace("%7E", "~");
    }
...
}

请求方法

public String twAuth() {
            String method = "POST";
            String url = "https://api.twitter.com/oauth/request_token";
            String oAuthConsumerKey = "2YhNLyum1VY10UrWBMqBnatiT";
            String oAuthConsumerSecret = ***CONSUMER_SECRET***;
            String oAuthCallback = "http://127.0.0.1:8080/twlogin";
            String oAuthNonce = String.valueOf(System.currentTimeMillis());
            String oAuthSignatureMethod = "HMAC-SHA1";
            String oAuthTimestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String oAuthVersion = "1.0";

            List<NameValuePair> allParams = new ArrayList<NameValuePair>();
            allParams.add(new BasicNameValuePair("oauth_callback", oAuthCallback));
            allParams.add(new BasicNameValuePair("oauth_consumer_key", oAuthConsumerKey));
            allParams.add(new BasicNameValuePair("oauth_nonce", oAuthNonce));
            allParams.add(new BasicNameValuePair("oauth_signature_method", oAuthSignatureMethod));
            allParams.add(new BasicNameValuePair("oauth_timestamp", oAuthTimestamp));
            allParams.add(new BasicNameValuePair("oauth_version", oAuthVersion));

            Collections.sort(allParams, new NvpComparator());

            StringBuffer params = new StringBuffer();
            for(int i=0;i<allParams.size();i++)
            {
                NameValuePair nvp = allParams.get(i);
                if (i>0) {
                    params.append("&");
                }
                params.append(nvp.getName() + "=" + OAuth.percentEncode(nvp.getValue()));
            }

            String signatureBaseStringTemplate = "%s&%s&%s";
            String signatureBaseString =  String.format(signatureBaseStringTemplate,
                    OAuth.percentEncode(method),
                    OAuth.percentEncode(url),
                    OAuth.percentEncode(params.toString()));

            String signatureKey = OAuth.percentEncode(oAuthConsumerSecret)+"&";

        SecretKeySpec signingKey = new SecretKeySpec(signatureKey.getBytes(), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(signatureBaseString.getBytes());
            String oAuthSignature = new String(Base64.encodeBase64(rawHmac));

        String authorizationHeaderValueTempl = "OAuth oauth_callback=\"%s\", " +
                    "oauth_consumer_key=\"%s\", " +
                    "oauth_nonce=\"%s\", " +
                    "oauth_signature=\"%s\", " +
                    "oauth_signature_method=\"%s\", " +
                    "oauth_timestamp=\"%s\", " +
                    "oauth_version=\"%s\"";

            String authorizationHeaderValue =String.format(authorizationHeaderValueTempl,
                    OAuth.percentEncode(oAuthCallback),
                    OAuth.percentEncode(oAuthConsumerKey),
                    OAuth.percentEncode(oAuthNonce),
                    OAuth.percentEncode(oAuthSignature),
                    OAuth.percentEncode(oAuthSignatureMethod),
                    OAuth.percentEncode(oAuthTimestamp),
                    OAuth.percentEncode(oAuthVersion));

        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("Authorization", authorizationHeaderValue);

        con.setDoOutput(true);

        int responseCode = con.getResponseCode();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        System.out.println(response.toString());

        return "aboutas";
    }


这里是一个twitter应用程序设置:
消费者密钥(API密钥):2YhNLyum1VY10UrWBMqBnatiT
回调URL:http://127.0.0.1:8080/twlogin
使用Twitter登录:是
网站http://127.0.0.1:8080

有人能帮我吗?我不知道该怎么办...

共有1个答案

璩涛
2023-03-14

我设置了错误的时间戳,因为我与Twitter服务器的时区不同。

这是设置真正oAuthTimestamp的代码:

HttpsURLConnection con = (HttpsURLConnection)
                    new URL("https://api.twitter.com/oauth/request_token").openConnection();
            con.setRequestMethod("HEAD");
            con.getResponseCode();
            String twitterDate= con.getHeaderField("Date");
            DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
            Date date = formatter.parse(twitterDate);
            String oAuthTimestamp = String.valueOf(date.getTime()/1000L);
 类似资料:
  • 我尝试通过https://api.twitter.com/oauth/request_token请求令牌,但总是得到401错误。 我通过curl进行测试(很容易看到发生了什么)。 curl--请求“POST”https://api.twitter.com/oauth/request_token“--标头”授权:OAuth OAuth\u回调=”http://www.domain.tld/blank

  • org.springframework.web.client.ResourceAccessException:POST请求“https://api.twitter.com/oauth/request_token”时的I/O错误:连接超时;嵌套异常java.net.SocketException:连接超时org.springframework.web.client.RestTemplate.do执行

  • 我写一个oauth与twitter的代码,我有401错误代码和"失败验证oauth签名和令牌"响应从twitter当我获取后请求到https://api.twitter.com/oauth/request_token.这是我的数据,我有: 我的步骤: 1.为签名准备的字符串 2.通过代码创建签名qQwIvFao9yeIQpi9ouz0oFi7/v8=: 3.最终授权标头(带转义引号): 问那些可能

  • 我正试图通过oAuth连接到Twitter。我正在向API发出POST请求https://api.twitter.com/oauth/request_token. 这是我的Base签名字符串示例 我用过这个工具http://quonos.nl/oauthTester/验证我的基本签名。 这里是对应的标题 我在我的MAC终端中尝试了以下命令 我得到401未经授权的错误。我试图设置oauth_call

  • 我在令牌使用者上得到以下错误。任何帮助解决这将是非常感谢的。多谢了。 “IDX10503:签名验证失败。 公共无效配置(IApplicationBuilder应用程序)

  • 当我试图从Java中的Magento获取数据时,我遇到了一个签名无效的问题。我的代码有什么问题: } } 签名是:NnRaB73FqCcFAAVB4evZtGkWE3k=附加的额外OAuth参数:{oauth_callback-