Hi,
I just start playing wiht spring social and I use this class for parsing facebook signed request and return a ConnectionData for use with ConnectionFactory.createConnection() method.
May be useful for you.
Code:
/*
* Copyright 2009-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package info.joseluismartin.facebook;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.social.connect.ConnectionData;
/**
* Facebook signed_request parser.
*
* @author Jose Luis Martin
*/
public class SignedRequestParser {
public static final String SIGN_ALGORITHM = "HMACSHA256";
private static final Log log = LogFactory.getLog(SignedRequestParser.class);
private String secret;
public ConnectionData parse(String signedRequest, String secret) {
ConnectionData data = null;
if (signedRequest == null)
return null;
try {
String[] requestArray = signedRequest.split("\\.");
if (requestArray.length == 2 && verifySign(requestArray[0], requestArray[1])) {
String payload = requestArray[1];
payload = payload.replace("-_", "+\\");
String decoded = new String(new Base64(true).decode(payload));
JSONObject json = JSONObject.fromObject(decoded);
String providerUserId = json.getString("user_id");
String accessToken = json.getString("oauth_token");
data = new ConnectionData("facebook", providerUserId, "", "", null, accessToken,
secret, null, null);
}
}
catch(Exception e) {
log.error(e);
}
return data;
}
/**
* Verify payload signature
*/
private boolean verifySign(String sign, String payload) {
SecretKeySpec sks = new SecretKeySpec(secret.getBytes(), SIGN_ALGORITHM);
Mac mac;
try {
mac = Mac.getInstance(SIGN_ALGORITHM);
mac.init(sks);
byte[] my = mac.doFinal(payload.getBytes());
byte[] their = new Base64(true).decode(sign);
return Arrays.equals(my, their);
} catch (NoSuchAlgorithmException nsae) {
log.error(nsae);
return false;
} catch (InvalidKeyException ike) {
log.error(ike);
return false;
}
}
/**
* @return the secret
*/
public String getSecret() {
return secret;
}
/**
* @param secret the secret to set
*/
public void setSecret(String secret) {
this.secret = secret;
}
}
Cheers