How to validate the FaceBook cookie in the server


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 =, "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;
				return false;

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

	private static String MD5(String text) throws NoSuchAlgorithmException,
			UnsupportedEncodingException {
		MessageDigest digest ="MD5");
		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)

		return buf.toString();


One comment

  1. Thanks, saved me some time 🙂

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

%d bloggers like this: