【问题标题】:Expired access_token received while converting request token of Twitter using oauth_token and oauth_verifier使用 oauth_token 和 oauth_verifier 转换 Twitter 的请求令牌时收到过期的 access_token
【发布时间】:2016-05-19 09:59:21
【问题描述】:

我正在尝试在 twitter 上使用 3 腿标志,因为我的步骤如下:

  1. 创建应用程序
  2. 获取 API 和密钥
  3. 获取请求令牌
  4. 获取访问令牌
  5. 如果需要,获取配置文件

我可以获得请求令牌:

    private String getRequestToken() throws Exception {
    String url = "https://api.twitter.com/oauth/request_token";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    String get_or_post = "POST";
    String oauth_signature_method = "HMAC-SHA1";
    String uuid_string = UUID.randomUUID().toString();
    uuid_string = uuid_string.replaceAll("-", "");
    String oauth_nonce = uuid_string; 
    Calendar tempcal = Calendar.getInstance();
    long ts = tempcal.getTimeInMillis();// get current time in milliseconds
    String oauth_timestamp = (new Long(ts / 1000)).toString();
    String parameter_string = "oauth_consumer_key=" + twitter_consumer_key + "&oauth_nonce=" + oauth_nonce
            + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp
            + "&oauth_version=1.0";
    System.out.println("parameter_string=" + parameter_string);
    String twitter_endpoint = "https://api.twitter.com/oauth/request_token";
    String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string);
    String oauth_signature = "";
    try {
        oauth_signature = computeSignature(signature_base_string, twitter_consumer_secret + "&");
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    String authorization_header_string = "OAuth oauth_consumer_key=\"" + twitter_consumer_key
            + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\""
            + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\"";
    System.out.println("authorization_header_string=" + authorization_header_string);

    // add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setRequestProperty("Authorization", authorization_header_string);
    System.out.println("---------------------------------------");
    System.out.println(authorization_header_string);
    System.out.println("---------------------------------------");
    // Send post request
    con.setDoOutput(true);

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

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

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

    // print result
    System.out.println(response.toString());
    String[] twitterResponse = response.toString().split("&");
    oauth_token = twitterResponse[0].substring(twitterResponse[0].indexOf("=") + 1);
    oauth_token_secret = twitterResponse[1].substring(twitterResponse[1].indexOf("=") + 1);
    oauth_callback_confirmed = twitterResponse[2].substring(twitterResponse[2].indexOf("=") + 1);
    return response.toString();
}

它的反应很好; 第 5 步是提供额外信息,即 x_auth_expires=0,这意味着收到的令牌已过期。因为我的下一个工作不正常 这是我获取 access_token 的代码

    public String getAccessToken(HttpServletRequest req) throws Exception {
    String url = "https://api.twitter.com/oauth/access_token";
    String oauthToken = (String) req.getParameter("oauth_token");
    String oauth_verifier = (String) req.getParameter("oauth_verifier");
    System.out.println("oauthToken----------"+oauthToken);
    System.out.println("oauth_verifier-----------"+oauth_verifier);
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    String get_or_post = "POST";
    String oauth_signature_method = "HMAC-SHA1";
    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();
    String parameter_string = "oauth_consumer_key=" + twitter_consumer_key + "&oauth_nonce=" + oauth_nonce
            + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp
            + "&oauth_token=" + oauthToken + "&oauth_version=1.0";
    System.out.println("parameter_string=" + parameter_string);
    String twitter_endpoint = "https://api.twitter.com/oauth/request_token";
    String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string);
    String oauth_signature = "";
    try {
        oauth_signature = computeSignature(signature_base_string, twitter_consumer_secret + "&");
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    String authorization_header_string = "OAuth oauth_consumer_key=\"" + twitter_consumer_key
            + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\""
            + oauth_nonce + "\",oauth_token=\"" + oauthToken + "\",oauth_version=\"1.0\",oauth_signature=\""
            + encode(oauth_signature) + "\"";
    System.out.println("authorization_header_string=" + authorization_header_string);
    String urlParameters = "oauth_verifier=" + oauth_verifier;

    // add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setRequestProperty("Authorization", authorization_header_string);
    System.out.println("---------------------------------------");
    System.out.println(authorization_header_string);
    System.out.println("---------------------------------------");
    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

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

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

    // print result
    System.out.println(response.toString());
    String[] responseOauthToken=response.toString().split("&");
    String oauth_token=responseOauthToken[0].substring(responseOauthToken[0].indexOf("=")+1);
    String screenname=responseOauthToken[3].substring(responseOauthToken[3].indexOf("=")+1);
    System.out.println("oauth_token---------"+oauth_token);
    System.out.println("screenname---------"+screenname);
    getProfile(oauth_token,screenname);
    return "";
}

验证个人资料的代码:

    public void getProfile(String oauthToken,String screenname) throws Exception {
    String url = "https://api.twitter.com/1.1/account/verify_credentials.json";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    String get_or_post = "GET";
    String oauth_signature_method = "HMAC-SHA1";
    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();
    String parameter_string = "oauth_consumer_key=" + twitter_consumer_key + "&oauth_nonce=" + oauth_nonce
            + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp
            +"&screen_name="+screenname+"&oauth_token="+oauthToken
            + "&oauth_version=1.0";
    System.out.println("parameter_string=" + parameter_string);
    String twitter_endpoint = "https://api.twitter.com/1.1/account/verify_credentials.json";
    String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string);
    String oauth_signature = "";
    try {
        oauth_signature = computeSignature(signature_base_string, twitter_consumer_secret + "&");
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    String authorization_header_string = "OAuth oauth_consumer_key=\"" + twitter_consumer_key
            + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\""
            + oauth_nonce +"\",oauth_token=\""+oauthToken+ "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\"";
    System.out.println("authorization_header_string=" + authorization_header_string);

    // add reuqest header
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setRequestProperty("Authorization", authorization_header_string);
    System.out.println("---------------------------------------");
    System.out.println(authorization_header_string);
    System.out.println("---------------------------------------");
    // Send post request
    con.setDoOutput(true);

    int responseCode = con.getResponseCode();
    System.out.println("\nSending '"+get_or_post+"' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

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

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

    // print result
    System.out.println(response.toString());

}

【问题讨论】:

    标签: java twitter twitter-oauth


    【解决方案1】:

    x_auth_expires 为 0 时,表示您的访问令牌没有过期,所以我认为这不是您的问题。

    您的问题(希望是唯一一个)似乎在getProfile() 这一行:

    oauth_signature = computeSignature(signature_base_string, twitter_consumer_secret + "&");
    

    您应该使用消费者密钥加上访问令牌密钥(由“&”连接)进行签名,但您只使用消费者密钥。当您接收并提取访问令牌时,您似乎甚至没有提取oauth_token_secret(访问oauth_token_secret 与请求oauth_token_secret 不同)。

    我还注意到,您目前正在按索引从响应中提取 oauth_tokenscreen_name。虽然属性的顺序似乎是一致的,但按名称获取它们是最安全的。

    实际上我确实看到了另一个问题。在getProfile() 中,screen_name 不应包含在参数字符串中,因为它不是参数,如果是,则需要按字典顺序排列。

    【讨论】:

      猜你喜欢
      • 2014-03-06
      • 2011-05-04
      • 2011-09-05
      • 2014-02-23
      • 1970-01-01
      • 2010-12-14
      • 2012-06-22
      • 1970-01-01
      • 2017-06-23
      相关资源
      最近更新 更多