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 doing some 4 hours of research i found out that the author had forgot to send a request to yahoo api’s to get GUID which is inturn used to get user profile data. I have modified 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("dj0yJmk9TXZDWVpNVVdGaVFmJmQ9WVdrOWMweHZXbkZLTkhVbWNHbzlNVEl5TWprd05qUTJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD0wMw--")
				.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! :)");

	}

	/**
	 *
	 */
	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 Next post i would provide a sample webapp where OAuth is used to authenticate with Yahoo/Google/Facebook. Njoy networking

OAuth with Facebook

Most of the applications over web these days need to get connected with each other. With the surge of Social Aware applications people started integrating all of their social application in one location.  Following is my attempt to solve the "Complex" but easy puzzle for novice developers

To start with i’ll demonstrate how to Login with Facebook and details of facebook user into your application

Lemme first explain what OAuth means in Brief.  Below is the diagram which explains

First we call Service provider with  ClientID  / CallBack URL  and Some additional Parameters based on Service provider you use

Then if we pass the right parameters then Service provider will give us a call back to given callback URL with Authorization Token and some parameter that states time to live

Now we can use this Authorization token in our subsequent requests to Service Provider Provided services

Here is example of facebook

Step 1

Goto Facebook developer Page

Step 2

Register your App. You will get you app key/secret etc

Step 3

Now goto this sample URL to get your token

Test with this URL

https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=168452316544703&redirect_uri=http%3A%2F%2Fnorthalley.com%2FTestWeb%2F/GetIPServlet&scope=user_photos,email,user_birthday,user_online_presence

Replace Corresponding Tokens for your Application

https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=CLIENT_ID&redirect_uri=REDIRECT_URL&scope=user_photos,email,user_birthday,user_online_presence

Step 4

Once you get Call back get the access_token from the request and store it

Example

—————–

http://northalley.com/TestWeb/GetIPServlet#access_token=168452316544703%7C2.WKMyHmlbzscco7HjrkJUMw__.3600.1304560800.1-100000131478113%7C9IpaoHOvCIfS4bqRZSqbu5-Rp8E&expires_in=5233

Step5

——–

Get user Data using the above token.

https://graph.facebook.com/me?access_token=168452316544703|2.WKMyHmlbzscco7HjrkJUMw__.3600.1304560800.1-100000131478113|9IpaoHOvCIfS4bqRZSqbu5-Rp8E

This gets user data in following format

{
   "id": "100000131478113",
   "name": "Ashwin Kumar",
   "first_name": "Ashwin",
   "last_name": "Kumar",
   "link": "http://www.facebook.com/profile.php?id=100000131478113",
   "birthday": "06/24/1984",
   "hometown": {
      "id": "103095893064172",
      "name": "Rajahmundry"
   },
   "location": {
      "id": "103129393060364",
      "name": "Allentown, Pennsylvania"
   },
   "work": [
      {
         "employer": {
            "id": "111926488822704",
            "name": "Freelancer"
         },
         "position": {
            "id": "130875350283931",
            "name": "CEO & Founder"
         },
         "start_date": "0000-04",
         "end_date": "0000-00"
      },
..............
...........
.............

Njoy integrating facebook to your application. Subsequent series will Cover Google/Twitter/LinkedIn/Yahoo Integration. Also writing a java library for this.. Will share that in opensource once done

Njoy playing with social apps….