Generating OAuth Token
-
Upload
imran-mehmood -
Category
Documents
-
view
214 -
download
0
Transcript of Generating OAuth Token
-
8/4/2019 Generating OAuth Token
1/8
How to generate OAuth Token.
http://code.google.com/p/qfacebookconnect/issues/detail?id=6
1) Send a post request tohttp://twitter.com/oauth/request_token2) Set the request Authorization header with the AuthorizeTokenString. You need to set this
header for every request [POST or GET].
3) Set the request Content-Type header with the application/x-www-form-urlencoded.You needto set this header for every request [POST or GET]
You can generate AuthorizeTokenString with the help of following code.
// call to method 1//request method (POST, GET)// url you want to hit// parameters if available otherwise pass array of parameters of size 0// token if available otherwise pass null
AuthorizeTokenString = generateAuthorizationHeader(requestMethod, url, params, token);
// method 1//need to tell abt method (POST, GET)//url to which you want to send request// PostParameter is class containing 2 properties (parameter and value)// OAuthToken is a class containing 2 properties (token and tokensecret)
private String generateAuthorizationHeader(String method, String url,PostParameter[] params, OAuthToken token) {
// time in milli seconds
long timestamp = System.currentTimeMillis() / 1000;
// just add a randomly generated no. and timestemp to generate nounce
long nonce = timestamp + Math.abs(RAND.nextInt());
// call to method 2
return generateAuthorizationHeader(method, url, params,String.valueOf(nonce), String.valueOf(timestamp), token);
}
//method 2
private String generateAuthorizationHeader(String method, String url,PostParameter[] params, String nonce, String timestamp, OAuthToken otoken) {
if (null == params) {
http://twitter.com/oauth/request_tokenhttp://twitter.com/oauth/request_tokenhttp://twitter.com/oauth/request_tokenhttp://twitter.com/oauth/request_token -
8/4/2019 Generating OAuth Token
2/8
params = new PostParameter[0];}
// vector containing the header parameter
Vector oauthHeaderParams = new Vector();
// CONSUMER_KEYconsumer key of your application registered with Twitter
oauthHeaderParams.addElement(new PostParameter("oauth_consumer_key",CONSUMER_KEY));
oauthHeaderParams.addElement(newPostParameter("oauth_signature_method", "HMAC-SHA1"));
oauthHeaderParams.addElement(new PostParameter("oauth_timestamp",timestamp));
oauthHeaderParams.addElement(new PostParameter("oauth_nonce",
nonce));
oauthHeaderParams.addElement(new PostParameter("oauth_version","1.0"));
if (null != otoken) {oauthHeaderParams.addElement(new PostParameter("oauth_token",
otoken.getToken()));}
Vector signatureBaseParams = new Vector();
//call to method 3. This method will add all the entries of second
vector to 1
st
one.addAll(signatureBaseParams, oauthHeaderParams);
############################################################ // method 3# privatevoidaddAll(Vector to, Vector from){# for(int i=0; i
-
8/4/2019 Generating OAuth Token
3/8
###########################################################
//call to method 5. This will parse all the querystring parameters from theurl and add them to the passing vector
parseGetParameters(url, signatureBaseParams);
StringBuffer base = new StringBuffer(method);base.append("&");
//call 1st method 6 and then 7.
base.append(encode(constructRequestURL(url)));base.append("&");
// call method 8 1st and then 7.base.append(encode(normalizeRequestParameters(signatureBaseParams)));
String oauthBaseString = base.toString();
// call to method 9.
String signature = generateSignature(oauthBaseString, otoken);
oauthHeaderParams.addElement(new PostParameter("oauth_signature",signature));
//call to method 10.return"OAuth " + encodeParameters(oauthHeaderParams, ",", true);
}
// method 5.privatevoidparseGetParameters(String url, Vector signatureBaseParams) {
int queryStart = url.indexOf("?");if (-1 != queryStart) {
//tokenizing the string with the &String[] queryStrs = StringUtil.split(url.substring(queryStart +
1), "&");
for (int i=0; i
-
8/4/2019 Generating OAuth Token
4/8
)));}
else {signatureBaseParams.addElement(
newPostParameter(URLDecoder.decode(split[0]), ""));
}}
}
}
// method 6.public String constructRequestURL(String url) {
int index = url.indexOf("?");if (-1 != index) {
url = url.substring(0, index);}int slashIndex = url.indexOf("/", 8);String baseURL = url.substring(0, slashIndex).toLowerCase();int colonIndex = baseURL.indexOf(":", 8);if (-1 != colonIndex) {
// url contains port numberif (baseURL.startsWith("http://") && baseURL.endsWith(":80")) {
// http default port 80 MUST be excludedbaseURL = baseURL.substring(0, colonIndex);
} elseif (baseURL.startsWith("https://") &&baseURL.endsWith(":443")) {
// http default port 443 MUST be excludedbaseURL = baseURL.substring(0, colonIndex);
}}url = baseURL + url.substring(slashIndex);
return url;}
// method 7.
public String encode(String value) {String encoded = null;try {
encoded = URLEncoder.encode(value, "UTF-8");} catch (UnsupportedEncodingException ignore) {}StringBuffer buf = new StringBuffer(encoded.length());
-
8/4/2019 Generating OAuth Token
5/8
char focus;for (int i = 0; i < encoded.length(); i++) {
focus = encoded.charAt(i);if (focus == '*') {
buf.append("%2A");} elseif (focus == '+') {
buf.append("%20");} elseif (focus == '%' && (i + 1) < encoded.length()
&& encoded.charAt(i + 1) == '7' && encoded.charAt(i + 2)== 'E') {
buf.append('~');i += 2;
} else {buf.append(focus);
}}return buf.toString();
}
// method 8.
public String normalizeRequestParameters(Vector params) {
//call 1st method 8-1 and then 8-2
return encodeParameters(sort(params));}
// method 8-1.sort the passing parameter
publicfinal Vector sort(Vector params){Vector v=new Vector();Enumeration e = params.elements();while (e.hasMoreElements()) {
PostParameter param =(PostParameter)e.nextElement();int i=0;for (i=0; i
-
8/4/2019 Generating OAuth Token
6/8
return encodeParameters(postParams, "&", false);}
// method 9.private String generateSignature(String data, OAuthToken token) {
byte[] mac = null;try {
String oauthSignature = "";if (null == token) {
//consumer key of your registered application
oauthSignature = encode(CONSUMER_SECRET) + "&";} else {
// consumer secret of your register applicationoauthSignature = encode(CONSUMER_SECRET) + "&" +
encode(token.getTokenSecret());}
//this code will generate hmac-sha1 based signature.
//use your api accordingly to generate this signature
HMAC m=new HMAC(new HMACKey(oauthSignature.getBytes()),newSHA1Digest());
byte[] bytes=data.getBytes("UTF-8");m.update(bytes, 0, bytes.length);mac = newbyte[m.getLength()];m.getMAC(mac, 0);
}catch (CryptoTokenException cte) {
// should never happen}catch (CryptoUnsupportedOperationException cuoe) {
// should never happen}catch(Exception e){}returnnew Base64().encode(mac);
}
-----------------------------------------------------
4) Encode the passing parameters and then write to stream.//call to method 11
query = encodeParameters(parameters)
5) Set the header for content length and set it with query.lenght(). You need to set this header forevery request [POST or GET]
6) You will get the similar response after sending request tohttp://twitter.com/oauth/request_token
http://twitter.com/oauth/request_tokenhttp://twitter.com/oauth/request_tokenhttp://twitter.com/oauth/request_token -
8/4/2019 Generating OAuth Token
7/8
oauth_token=94tgf5JeAF5aCSqzSFZQrzJON2DXPIXKlxkkOiRcQA&oauth_token_secret=9sAHn709oIuBNgu9FbLAqiPXPmAVyvPSsYkm7jGYsM&oauth_callback_confirmed=true
7)Initialize OAuthToken after extracting oauth_token andoauth_token_secret from the above response
8) Send a GET Request to http://twitter.com/oauth/authorize?oauth_token=" +oToken.getToken() and this will return you html based response
9) Take parameter array of size 410)Extract the required data from response
PostParameter [] params = new PostParameter[4];
params[0] = new PostParameter("authenticity_token"
//call to method 12. Response is html string which we get by calling above
url., catchPattern(response,
"\"authenticity_token\" type=\"hidden\" value=\"", "\" />"));
params[1] = new PostParameter("oauth_token",
catchPattern(response,"name=\"oauth_token\" type=\"hidden\"value=\"","\" />"));
params[2] = newPostParameter("session[username_or_email]", username);
params[3] = new PostParameter("session[password]",
password);
11)Get the authorize url from the responseString authorizeURL = catchPattern(response, "
-
8/4/2019 Generating OAuth Token
8/8
pin = catchPattern(response, "\n ","\n");
15)Send a POST request tohttp://twitter.com/oauth/access_tokenwith the following parameternew PostParameter[]{new PostParameter("oauth_verifier", pin)}
16)The above request will return you a response like
oauth_token=94tgf5JeAF5aCSqzSFZQrzJON2DXPIXKlxkkOiRcQA&oauth_token_secret=9sAHn709oIuBNgu9FbLAqiPXPmAVyvPSsYkm7jGYsM
17) Initialize OAuthToken with above response. This is yourrequired token and persist this token. You need to send thistoken with every request [timeline, tweeting etc]
http://twitter.com/oauth/access_tokenhttp://twitter.com/oauth/access_tokenhttp://twitter.com/oauth/access_tokenhttp://twitter.com/oauth/access_token