Twitter oauth无效的oauth_verifier参数

时间:2015-05-30 19:11:16

标签: java twitter oauth

我正在使用Java实现oauth以下序列:

1)发送POST https://api.twitter.com/oauth/request_token(带回调) Twitter响应包含oauth_token,oauth_token_secret和oauth_callback_confirmed = true

2)重定向到https://api.twitter.com/oauth/authenticate?oauth_token = {oauth_token来自Twitter上的回复}

3)出现Twitter登录表单,我点击“登录”按钮。

4)Twitter重定向到{callback_url}?oauth_token = {此标记等于来自oauth / request_token响应的标记}& oauth_verifier = {verifier}

5)POST https://api.twitter.com/oauth/access_token 使用Oauth头包含oauth_token,消息正文包含oauth_verifier = {return verifier}

6)Twitter响应=处理您的OAuth请求时出错:oauth_verifier参数无效

oauth_verifier有什么问题?

计算签名方法:

private static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException {
        SecretKey secretKey = null;

        byte[] keyBytes = keyString.getBytes();
        secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);

        byte[] text = baseString.getBytes();

        return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
    }

第一次请求的代码:

String oauth_signature_method = "HMAC-SHA1";

    // generate any fairly random alphanumeric string as the "nonce".
    String uuid_string = UUID.randomUUID().toString();
    uuid_string = uuid_string.replaceAll("-", "");
    String oauth_nonce = uuid_string;

    // get the timestamp
    Calendar tempcal = Calendar.getInstance();
    long ts = tempcal.getTimeInMillis();
    String oauth_timestamp = (new Long(ts / 1000)).toString(); 
    String parameter_string = "oauth_callback=" + OauthConstants.TWITTER_OAUTH_CALLBACK 
            + "&oauth_consumer_key=" + OauthConstants.TWITTER_OAUTH_CONSUMER_KEY
            + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method="
            + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_version=1.0";
    String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string);
    String oauth_signature = "";

    try {
        oauth_signature = computeSignature(signature_base_string, OauthConstants.TWITTER_OAUTH_CONSUMER_SECRET + "&");  
    } catch (GeneralSecurityException | UnsupportedEncodingException e) {
       ...}

String twitter_endpoint = "https://api.twitter.com/oauth/request_token";
String authorization_header_string = "OAuth oauth_callback=\"" + OauthConstants.TWITTER_OAUTH_CALLBACK
                + "\",oauth_consumer_key=\"" + OauthConstants.TWITTER_OAUTH_CONSUMER_KEY
                + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                + encode(oauth_signature) + "\"";

// Apache httpcore 4.4.1
HttpProcessor httpproc = HttpProcessorBuilder.create()
                .add(new RequestContent())
                .add(new RequestTargetHost())
                .add(new RequestConnControl())
                .add(new RequestUserAgent("ApacheHttp/1.1"))
                .add(new RequestExpectContinue(true)).build();

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpCoreContext context = HttpCoreContext.create();
        HttpHost host = new HttpHost(twitter_endpoint_host, 443); 
        DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);

        context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn);
        context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, host);

try {
                // initialize the HTTPS connection
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, null, null);
                SSLSocketFactory ssf = sslcontext.getSocketFactory();
                Socket socket = ssf.createSocket();
                socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                conn.bind(socket);

                BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path, HttpVersion.HTTP_1_1);
                request2.setEntity(new StringEntity("", "UTF-8"));
                request2.addHeader("Authorization", authorization_header_string); 
                httpexecutor.preProcess(request2, httpproc, context);
                HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                httpexecutor.postProcess(response2, httpproc, context);
} catch(Exception e) {} ... 

第二次请求的代码(重定向到https oauth / authenticate)

public JSONObject getTwitterAuthorizationCodeFromRequestToken(String oauth_token) {
...
        String twitter_endpoint = "https://api.twitter.com/oauth/authenticate";

        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect(twitter_endpoint  + "?oauth_token=" + encode(oauth_token));
        } catch (IOException ex) {...}
...
    }

第3次请求的代码(POST oauth / access_token)

    public JSONObject getTwitterAccessTokenFromAuthorizationCode(String verifier_or_pin, String oauth_token) {
    ...
 String oauth_signature_method = "HMAC-SHA1";

    // generate any fairly random alphanumeric string as the "nonce". Nonce = Number used ONCE.
    String uuid_string = UUID.randomUUID().toString();
    uuid_string = uuid_string.replaceAll("-", "");
    String oauth_nonce = uuid_string; 

    Calendar tempcal = Calendar.getInstance();
    long ts = tempcal.getTimeInMillis();
    String oauth_timestamp = (new Long(ts / 1000)).toString(); 

    // the parameter string must be in alphabetical order
    String parameter_string = "oauth_consumer_key=" + OauthConstants.TWITTER_OAUTH_CONSUMER_KEY 
                            + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method
                            + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";

    String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string);

    String oauth_signature = "";
    try {
        oauth_signature = computeSignature(signature_base_string, OauthConstants.TWITTER_OAUTH_CONSUMER_SECRET + "&");
    } catch (GeneralSecurityException | UnsupportedEncodingException e) {
        ...
    }

    String authorization_header_string = "OAuth oauth_consumer_key=\"" + OauthConstants.TWITTER_OAUTH_CONSUMER_KEY  
                                               + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                                               + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" 
                                               + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

    HttpProcessor httpproc = HttpProcessorBuilder.create()
                    .add(new RequestContent())
                    .add(new RequestTargetHost())
                    .add(new RequestConnControl())
                    .add(new RequestUserAgent("ApacheHttp/1.1"))
                    .add(new RequestExpectContinue(true)).build();

            HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
            HttpCoreContext context = HttpCoreContext.create();
            HttpHost host = new HttpHost(twitter_endpoint_host, 443); 
            DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);

            context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn);
            context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, host);

    try {
                    SSLContext sslcontext = SSLContext.getInstance("TLS");
                    sslcontext.init(null, null, null);
                    SSLSocketFactory ssf = sslcontext.getSocketFactory();
                    Socket socket = ssf.createSocket();
                    socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                    conn.bind(socket);

                    BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path);
                    // Including oauth_verifier value to request body
                    request2.setEntity(new StringEntity("oauth_verifier=" + encode(verifier_or_pin), "UTF-8"));
                    request2.addHeader("Authorization", authorization_header_string);
                    httpexecutor.preProcess(request2, httpproc, context);
                    HttpResponse response2 = httpexecutor.execute(request2, conn, context);
... 
    }

1 个答案:

答案 0 :(得分:3)

我的JavaScript代码库经历了完全相同的情况。经过一天的挣扎,我找到了解决错误的解决方案。这只是添加了一个“内容类型”标题,其值为“ application / x-www-form-urlencoded ”。

我的代码曾经正常运行,但它在过去几个月停止运作。我的猜测是Twitter最近更改了OAuth处理的实现,迫使我们明确添加内容类型。