public static FacebookCookie decode ( String cookie , String appSecret ) { // Parsing and verifying signature seems to be poorly documented, but here's what I've found: // Look at parseSignedRequest() in https://github.com/facebook/php-sdk/blob/master/src/base_facebook.php // Python version: https://developers.facebook.com/docs/samples/canvas/ try { String [ ] parts = cookie . split ( "\\." ) ; byte [ ] sig = Base64 . decodeBase64 ( parts [ 0 ] ) ; byte [ ] json = Base64 . decodeBase64 ( parts [ 1 ] ) ; byte [ ] plaintext = parts [ 1 ] . getBytes ( ) ; // careful, we compute against the base64 encoded version FacebookCookie decoded = MAPPER . readValue ( json , FacebookCookie . class ) ; // "HMAC-SHA256" doesn't work, but "HMACSHA256" does. String algorithm = decoded . algorithm . replace ( "-" , "" ) ; SecretKey secret = new SecretKeySpec ( appSecret . getBytes ( ) , algorithm ) ; Mac mac = Mac . getInstance ( algorithm ) ; mac . init ( secret ) ; byte [ ] digested = mac . doFinal ( plaintext ) ; if ( ! Arrays . equals ( sig , digested ) ) throw new IllegalStateException ( "Signature failed" ) ; return decoded ; } catch ( Exception ex ) { throw new IllegalStateException ( "Unable to decode cookie" , ex ) ; } }
Decodes and validates the cookie .