OAuth using Scribe with Yahoo API
This is sequence of my previous post but now with Yahoo.
I have downloaded Scribe example source code to get authenticated with Yahoo. But the default example was not working. After several hours of research, I found out that the author had forgotten to send a request to Yahoo APIs to get a GUID, which is in turn used to get user profile data. I have modified the code to fix that and here is the working code.
package org.scribe.examples;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Scanner;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.YahooApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class YahooExample {
private static String PROTECTED_RESOURCE_URL =
"http://social.yahooapis.com/v1/user/GUID/profile?format=json";
public static void main(String[] args) {
OAuthService service = new ServiceBuilder()
.provider(YahooApi.class)
.apiKey("dj0yJmk9TXZDWVpNVVdGaVFmJmQ9WVdrOWMweHZXbkZLT
khVbWNHbzlNVEl5TWprd05qUTJNZy0tJnM9Y29uc3VtZXJzZWNyZX
QmeD0wMw--")
.apiSecret("262be559f92a2be20c4c039419018f2b48cdfce9")
.build();
Scanner in = new Scanner(System.in);
System.out.println("=== Yahoo's OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
System.out.println("Now go and authorize Scribe here:");
System.out.println(service.getAuthorizationUrl(requestToken));
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: "
+ accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request1 = new OAuthRequest(Verb.GET,
"http://social.yahooapis.com/v1/me/guid?format=xml");
service.signRequest(accessToken, request1);
Response response1 = request1.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response1.getCode());
System.out.println(response1.getBody());
PROTECTED_RESOURCE_URL = PROTECTED_RESOURCE_URL.replaceAll("GUID",
parseYahooGUIDResposne(response1.getBody()));
System.out.println("PROTECTED_RESOURCE_URL "
+ PROTECTED_RESOURCE_URL);
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET,
PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
request.addHeader("realm", "yahooapis.com");
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
System.out
.println("Thats it man! Go and build something
awesome with Scribe! <img src="http://s2.wp.com/wp-includes/
images/smilies/icon_smile.gif" alt=":)" class="wp-smiley" /> ");
}
/**
*
*/
private static String parseYahooGUIDResposne(String data) {
// get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using builder to get DOM representation of the XML file
Document dom = db.parse(new ByteArrayInputStream
(data.getBytes()));
Element rootElement = dom.getDocumentElement();
return getGUID(rootElement);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (SAXException se) {
se.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
/**
* I take an employee element and read the values in, create
* an Employee object and return it
*/
private static String getGUID(Element guidEl) {
// for each <employee> element get text or int values of
// name ,id, age and name
String name = getTextValue(guidEl, "value");
// System.out.println("Name: "+name);
return name;
}
/**
* I take a xml element and the tag name, look for the tag and get
* the text content
* i.e for <?xml version="1.0" encoding="utf-8"?>
* <guid xmlns="http://social.yahooapis.com/v1/schema.rng"
* xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
* yahoo:uri="http://social.yahooapis.com/v1/me/guid">
* <value>4QWOBUCQHETEL34LSRUKJEV5W4</value></guid> xml snippet if
* the Element points to employee node and tagName is 'name' I will return John
*/
private static String getTextValue(Element ele, String tagName) {
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if (nl != null && nl.getLength() > 0) {
Element el = (Element) nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}
return textVal;
}
/**
* Calls getTextValue and returns a int value
*/
private static int getIntValue(Element ele, String tagName) {
// in production application you would catch the exception
return Integer.parseInt(getTextValue(ele, tagName));
}
}
In my next post, I will provide a sample web app where OAuth is used to authenticate with Yahoo/Google/Facebook.
Enjoy networking.
发表评论
jHcWXM It as hard to find knowledgeable people for this topic, but you sound like you know what you are talking about! Thanks
cw8Qgn It is in reality a nice and useful piece of info. I am satisfied that you shared this helpful tidbit with us. Please keep us informed like this. Thank you for sharing.
z1JXGE Wow! Thank you! I continually needed to write on my site something like that. Can I include a portion of your post to my website?
vs6Xhx Muchos Gracias for your post.Much thanks again.
高級腕時大特価
バーバリー、アルマーニ、コーチ、ルイ·ヴィトン、D&G、オメガ…
若手サラリーマンでもそんな高級ブランドの腕時計を持っていることが珍しくなかった。
雅優ブランド広場、高級腕時計大特価。
興味のある方は是非下記へご連絡ください。
ご連絡お待ちしています。JR8Crr In my opinion it is obvious. You did not try to look in google.com?
4sfSUX I have recently started a website, the information you provide on this site has helped me greatly. Thanks for all of your time & work.
W3dTtv F*ckin' amazing things here. I'm very glad to peer your post. Thank you so much and i'm having a look forward to touch you. Will you please drop me a e-mail?
Cmv7Ra Fantastic website. Plenty of useful info here. I am sending it to several friends ans additionally sharing in delicious. And naturally, thank you in your effort!
5Iht6K Hello there, You've done an incredible job. I'll certainly digg it and for my part recommend to my friends. I'm sure they will be benefited from this site.
Uf6WL8 Thanks again for the blog article.Thanks Again. Awesome.
f6eesH Im thankful for the blog article.Really thank you! Really Cool.
Iu9p64 Thanks for the post.Thanks Again. Really Great.
jjUO8K wow, awesome blog.Really thank you!
XIfcMe This is one awesome blog post.Really looking forward to read more. Fantastic.
7sSqKA Major thanks for the blog.Thanks Again. Great.
Thank you for your article post.Really looking forward to read more. Fantastic.
9qmp6C I really like and appreciate your blog post.Thanks Again. Awesome.
yyDeJT I am so grateful for your blog article.Thanks Again. Will read on...
fGNp1m Im grateful for the blog.Really thank you! Really Great.
vL7r4O Really enjoyed this blog.Thanks Again.
機会はありません会報とデジタルマガジンの最新の日間の背中があったので、それはあなたのナイキshox産業の範囲内で起こっているいくつかの新しいアイテムを見つけることができるかどうか見るために、アフィリエイトマーケティング担当者のための時間ですこの構成について掲載中の時代遅れのマーケティング担当者と新しい消費者に分散するかもしれませんこれらの同じ出版物、最近提示されたすべての商品としての日付として多く
転送することで、かかとパッドを発売しましたいくつかのプロ選手のワックス靴使用と彼らが遊ぶたびに優れた技術を利用することに決めるワックスの最大の売りは、ゴルフシューズメンズゴルフシューズをこの過去の年menwereと疑いなしで残りはスポーツのトップで長年にわたります
ジョナサンtoews夢を延期しましたあなたはあなたの夢のジャージのサイクルを壊す方法が、ジョナサン?toewsジャージーはあなたのラ
販売されている。燃える作業の過程において、カロリーを理解するとき、腕時計は基本的に傷がありますあなたの現在の体重とあなたの楕円形の作業強度のあなたのカロリーを決定するものであるしたがって、個々の180 lbの重さの作品から個々の260ポンドの重さとしては非常に同じ強度であるならば、より大きなポンドの人間の余分のカロリーを燃やすとクロストレーナー以外のあなたの最近の過剰体重でプログラムされることがで
ビスであるかもしれないと尊敬されたテレマーケターによって合法的に販売されているの数scamsalthough、消費者保護の部門の7つの場所を正確に同定されたが詐欺が起こることができる最も害と消費者の財布の方へのコスト無料の賞を提供します:得なければ電話接触を持っているあなたが全く自由な賞を獲得したが、慎重になる一般的にあなたがそれらを提供を確保する実質的な処理費用、などの事情の送料を見つけ、会員費
たのバッテリーライフスタイルの危険の代わりとして、それは本当に決してit.threeによる過充電開始からあなたのバッテリーをガードする優れた思想であるバッテリーは本当にが下にあるとき、あなたの電話料金なので、今日は完全に無料です、そして、あなたの充電器に接続する悲しいことに、これは本当にいけないあなたが持っている必要があるからであるあなたの携帯電話のバッテリーは消耗してその費用を欠いた充電系統それHPayX1 This is one awesome post.Really looking forward to read more. Much obliged.
jGNrU5 Major thankies for the post.Much thanks again. Want more.
mOxZCG I am so grateful for your article post.Thanks Again. Want more.