Parsing Facebook signed_request using Java returns invalid JSON

I am trying to parse the Facebook signed_request inside the Java Servlet doPost. And I decode the signed request using commons-codec-1.3 Base64. Here is the code I used for this in servlet doPost

 String signedRequest = (String) req.getParameter("signed_request"); String payload = signedRequest.split("[.]", 2)[1]; payload = payload.replace("-", "+").replace("_", "/").trim(); String jsonString = new String(Base64.decodeBase64(payload.getBytes())); 

when i System.out jsonString it is distorted. Sometimes it skips the ending } JSON sometimes it skips "} at the end of the line.

How can I get the correct JSON response from Facebook?

+6
source share
4 answers

facebook uses Base64 for URLs, and you're probably trying to decode text using the standard Base64 algorithm. among other things, the URL option does not require padding with "=".

  • you can add required characters to the code (addition, etc.)
  • you can use commons-codec 1.5 (new Base64 (true)) where they added support for this encoding.
+7
source

Facebook sends you "loose" Base64 values ​​(standard "URL"), and this is problematic for Java decoders that don't expect this. You can say that you have a problem when the Base64 encoded data you want to decode has a length that is not a multiple of 4.

I used this function to commit values:

 public static String padBase64(String b64) { String padding = ""; // If you are a java developer, *this* is the critical bit.. FB expects // the base64 decode to do this padding for you (as the PHP one // apparently // does... switch (b64.length() % 4) { case 0: break; case 1: padding = "==="; break; case 2: padding = "=="; break; default: padding = "="; } return b64 + padding; } 
+4
source

I have never done this in Java, so I don’t have a complete answer, but the fact that you sometimes lose one or sometimes two characters from the end of the line suggests that this may be a problem with Base64 add-on. You might want to infer the payload value and see if "=" ever ends, then jsonString will not be "}", and when the payload ends with "==", then jsonString will not be ""}. If it looks like something is going wrong with the interpretation of equal signs at the end of the payload, which should represent empty bits.

Edit: For further thought, I believe this is because Facebook uses Base64 URL encoding (which does not add = like pad characters) instead of regular Base64, while your decoding function expects regular Base64 with trailing = chars.

+1
source

I upgraded to common-codec-1.5 using code very similar to this one and I am not experiencing this problem. Have you confirmed that the payload is really distorted when using an online decoder?

+1
source

Source: https://habr.com/ru/post/897251/


All Articles