简体   繁体   中英

Expired access_token received while converting request token of Twitter using oauth_token and oauth_verifier

I am trying to use 3 legged sign with twitter for I am steps are as follows:

  1. create app
  2. get API and secret
  3. get request token
  4. get access token
  5. fetch profile if required

I am able to get request token:

    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();
}

its response is coming fine; 5th step is giving an extra information ie x_auth_expires=0 which means that the token received is expired. because of which my next is not working fine here is my code to fetch 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 "";
}

Code for verifying a profile:

    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());

}

When x_auth_expires is 0, it means that your access token doesn't have an expiration so I don't believe that is your problem.

Your problem (hopefully the only one) appears to be on this line in getProfile() :

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

You should be signing with the consumer secret plus the access token secret (joined by '&') but you are only using the consumer secret. It appears that you aren't even extracting oauth_token_secret when you receive and extract the access token (the access oauth_token_secret is not the same as the request oauth_token_secret ).

I also note that you are currently extracting oauth_token and screen_name from the response by index. While the ordering of properties seems consistent, it would be safest to get them by name.

Actually I do see another issue. In getProfile() , screen_name should not be included in your parameter string because it is not a parameter, and if it were it would need to be in lexicographic order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM