here's a sample java class that tries to do three legged oauth with Yahoo.
using Google's client to sign it with HMAC-SHA1.
When you run it -> it stops with the url to go to for verification and waits for user input to confirm verification.
All of that runs fine,
The last request fails with an "Invalid Credentials" response.
Am not sure what's wrong here, possibly how the authorization header is being constructed???
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.ProxyHost;
import org.apache.commons.httpclient.methods.GetMethod;
import com.google.gdata.client.authn.oauth.OAuthHelper;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthUtil;
public class YahooOAuth {
static String key = "KKKKKKKKEEEEEEEEEYYYYY";
static String secret = "SSSSSSSECCCCCCCRETTTT";
static String appId = "APPIDDD";
static String callback = "CALLLBACCK";
/**
*
* @return
* @throws MalformedURLException
* @throws Exception
*/
public static Map getLoginUrl() throws MalformedURLException, Exception {
Map get_request_token = new HashMap();
String reqUrl = "https://api.login.yahoo.com/oauth/v2/"
+ "get_request_token?" + "oauth_nonce="
+ new Random().nextInt() + "&oauth_timestamp="
+ ((int) (System.currentTimeMillis() / 1000))
+ "&oauth_consumer_key=" + key
+ "&oauth_signature_method=plaintext" + "&oauth_signature="
+ secret+"%26" + "&oauth_version=1.0";
String resp = getResponse(reqUrl);
StringTokenizer st = new StringTokenizer(resp, "&");
while (st.hasMoreTokens()) {
String token = st.nextToken();
get_request_token.put(token.substring(0, token.indexOf("=")), token
.substring(token.indexOf("=") + 1, token.length()));
}
System.out.println("Map got : " + get_request_token);
return get_request_token;
}
private static String getResponse(String reqUrl) throws Exception{
HttpClient client = new HttpClient();
/*boolean usingProxy = new Boolean(PropertyStore.getBaseProperty("using_proxy")).booleanValue();
if(usingProxy)
{
ProxyHost proxy = new ProxyHost(PropertyStore.getBaseProperty("proxy"),
new Integer(PropertyStore.getBaseProperty("proxy_port")).intValue());
client.getHostConfiguration().setProxyHost(proxy);
}*/
GetMethod getm = new GetMethod(reqUrl);
client.executeMethod(getm);
return getm.getResponseBodyAsString();
}
public static Map getAccessTokenMap(String authToken, String osecret)
throws Exception {
Map accessMap = new HashMap();
String accUrl = "https://api.login.yahoo.com/oauth/v2/get_token?"
+ "&oauth_consumer_key=" + key
+ "&oauth_signature_method=plaintext" + "&oauth_signature="
+ secret +"%26"+osecret + "&oauth_version=1.0" + "&oauth_nonce="
+ new Random().nextInt() + "&oauth_timestamp="
+ ((int) (System.currentTimeMillis() / 1000)) + "&oauth_token="
+ authToken;
String resp = getResponse(accUrl);
System.out.println(resp);
StringTokenizer st = new StringTokenizer(resp, "&");
while (st.hasMoreTokens()) {
String token = st.nextToken();
accessMap.put(token.substring(0, token.indexOf("=")), token
.substring(token.indexOf("=") + 1, token.length()));
}
System.out.println(accessMap);
return accessMap;
}
public static void main(String[] args) throws MalformedURLException,
Exception {
// System.out.println(getLoginUrl());
Map<String, String> reqMap = getLoginUrl();
String loginUrl = URLDecoder.decode((String) reqMap
.get("xoauth_request_auth_url"))
+ "&oauth_callback=" + callback;
System.out.println(loginUrl);
getStringFromShell("Verify identity at "+loginUrl);
Map<String, String> accMap = getAccessTokenMap(reqMap
.get("oauth_token"), reqMap.get("oauth_token_secret"));
String guid = accMap.get("xoauth_yahoo_guid");
String url = "http://social.yahooapis.com/v1/user/" + guid
+ "/profile?format=json";
/*Map params = new HashMap(accMap);
params.put("oauth_signature_method", "HMAC-SHA1");
params.put("oauth_nonce", new Random().nextInt() + "");
params.put("oauth_timestamp", (int) (System.currentTimeMillis() / 1000)
+ "");
params.remove("oauth_signature");*/
OAuthParameters oaup = new OAuthParameters();
oaup.setOAuthCallback(callback);
oaup.setOAuthConsumerKey(key);
oaup.setOAuthConsumerSecret(secret);
oaup.setOAuthNonce(OAuthUtil.getNonce());
oaup.setOAuthTimestamp(OAuthUtil.getTimestamp());
oaup.setOAuthToken(accMap.get("oauth_token"));
oaup.setOAuthTokenSecret(accMap.get("oauth_token_secret"));
String baseString = OAuthUtil
.getSignatureBaseString(url, "GET", oaup.getBaseParameters());
System.out.println("Base String " + baseString);
OAuthHmacSha1Signer sgner = new OAuthHmacSha1Signer();
String signature = (sgner.getSignature(baseString, oaup));
/*GET
http://social.yahooapis.com/v1/user/abcdef...ile?format=json Authorization: OAuth
realm="yahooapis.com",
oauth_consumer_key="dj0yJmk9nM9Y29uc3VtZXJzZWNyZXQmeD1lMg--",
oauth_nonce="24829.2331",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1219450170",
oauth_token="A%3DuqkiebGpiTJl7ThQxU.jDXXaETYyfEy3xAKPyoavokwOOcZcz8Xs_l1Nvnl._
KmCEVCeLkxxT1Y6BgRqf5f98sQWHklBM_anetveR7okK_M_5XEmQ1_1reo3UgKQULT_dQT8Gao3.
Rrgz5rJxgmnYrhdWWdfgTdMQVzpbJT2aGkz59NTK1O8yXVE1EvZUCqju7WiFYu.WHNEw.9TWq3g--",
oauth_version="1.0",
oauth_signature="O2AQipLITO0aYHKZc9266RzC94%3D"*/
oaup.setOAuthSignature(signature);
oaup.setOAuthSignatureMethod("HMAC-SHA1");
oaup.setRealm("yahooapis.com");
/*String p1 = oaup.getBaseParameters().toString().replace("{", "").replace("}","").replace(", ","&");
String p2 = oaup.getExtraParameters().toString().replace("{", "").replace("}","").replace(", ","&");*/
HttpClient client = new HttpClient();
/*boolean usingProxy = new Boolean(PropertyStore.getBaseProperty("using_proxy")).booleanValue();
if(usingProxy)
{
ProxyHost proxy = new ProxyHost(PropertyStore.getBaseProperty("proxy"),
new Integer(PropertyStore.getBaseProperty("proxy_port")).intValue());
client.getHostConfiguration().setProxyHost(proxy);
}*/
GetMethod getm = new GetMethod(url.toString());
/* String authString = "OAuth \n";
authString = (authString+p1+p2).replace("=","=\"").replace("&", "\"\n");
System.out.println(authString);*/
Map params = new LinkedHashMap();
params.put(OAuthParameters.OAUTH_CONSUMER_KEY, oaup.getOAuthConsumerKey());
params.put(OAuthParameters.OAUTH_NONCE_KEY, oaup.getOAuthNonce());
params.put(OAuthParameters.OAUTH_SIGNATURE_METHOD_KEY, oaup.getOAuthSignatureMethod());
params.put(OAuthParameters.OAUTH_TIMESTAMP_KEY, oaup.getOAuthTimestamp());
params.put(OAuthParameters.OAUTH_TOKEN_KEY, oaup.getOAuthToken());
params.put("oauth_version","1.0");
params.put(OAuthParameters.OAUTH_SIGNATURE_KEY, oaup.getOAuthSignature());
String aHeader = getAuthorizationHeader(oaup.getRealm(), params);
System.out.println("HEader "+aHeader);
Header hdr = new Header("Authorization", aHeader);
getm.addRequestHeader(hdr);
//client.
/* getm.addRequestHeader(OAuthParameters.REALM_KEY, oaup.getRealm());
//getm.addRequestHeader("oauth_version", "1.0");
getm.addRequestHeader(OAuthParameters.OAUTH_SIGNATURE_KEY, oaup.getOAuthSignature());*/
client.executeMethod(getm);
System.out.println(getm.getResponseBodyAsString());
System.out.println("URL : "+url);
}
public static String getStringFromShell(String prompt) {
try {
System.out.print(prompt);
return new BufferedReader(new InputStreamReader(System.in))
.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/** The encoding used to represent characters as bytes. */
public static final String ENCODING = "UTF-8";
public static String percentEncode(String s) {
if (s == null) {
return "";
}
try {
return URLEncoder.encode(s, ENCODING)
// OAuth encodes some characters differently:
.replace("+", "%20").replace("*", "%2A")
.replace("%7E", "~");
// This could be done faster with more hand-crafted code.
} catch (UnsupportedEncodingException wow) {
throw new RuntimeException(wow.getMessage(), wow);
}
}
/**
* Construct a WWW-Authenticate or Authentication header value, containing
* the given realm plus all the parameters whose names begin with "oauth_".
*/
public static String getAuthorizationHeader(String realm, Map parameters) throws IOException {
StringBuilder into = new StringBuilder();
if (realm != null) {
into.append(" realm=\"").append(percentEncode(realm)).append('"');
}
if (parameters != null) {
for (Iterator iterator = parameters.entrySet().iterator(); iterator.hasNext()

{
Map.Entry parameter = (Map.Entry) iterator.next();
String name = parameter.getKey().toString();
if (name.startsWith("oauth_")) {
if (into.length() > 0) into.append(",\n");
into.append(" ");
into.append(percentEncode(name)).append("=\"");
into.append(percentEncode(parameter.getValue().toString())).append('"');
}
}
}
return "OAuth \n" + into.toString();
}
}