How to validate the FaceBook cookie in the server

Hi,

Now I am changing my out of work coding to a social mashup with GWT, GAE, Facebook API and so on.

Something that is quite difficult is how to validate the facebook cookie in the server, in order to view if the request is made by a FaceBook user within your application.

Here is the code, you need to play with a hash of the cookie content, the secret key of the application and the result of mixing those two together.


public class FaceBookSecurity {

	public static boolean ValidateFBCookie(HttpServletRequest request) {

		Cookie[] cookies = request.getCookies();
		Cookie fbCookie = null;
		try {

			for (Cookie c : cookies) {
				if (c.getName().equals(
						"fbs_" + ApplicationConstants.FacebookApiKey)) {
					fbCookie = c;
				}
			}

			if (fbCookie == null)
				return false;

			String fbCookieValue = fbCookie.getValue();

			fbCookieValue = java.net.URLDecoder.decode(fbCookieValue, "UTF-8");//important, here I lost a few hours.

			String[] stringArgs = fbCookieValue.trim().split("&");

			String md5Hash = "";
			String sig = "";

			for (String s : stringArgs) {
				String key = s.split("=")[0];
				String value = s.split("=")[1];

				if (!key.equals("sig")) {
					md5Hash = md5Hash + key + '=' + value;
				} else {
					sig = value;
				}
			}

			md5Hash = MD5(md5Hash + ApplicationConstants.FacebookSecretKey);

			if (md5Hash.equals(sig))
				return true;
			else
				return false;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	private static String MD5(String text) throws NoSuchAlgorithmException,
			UnsupportedEncodingException {
		MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
		digest.reset();
		digest.update(text.toString().getBytes());
		byte[] hash = digest.digest();
		StringBuffer buf = new StringBuffer();

		for (int i = 0; i < hash.length; i++) {
			String hex = Integer.toHexString(0xff & hash[i]);
			if (hex.length() == 1)
				buf.append('0');
			buf.append(hex);
		}

		return buf.toString();
	}


Advertisements

One comment

  1. Thanks, saved me some time 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: