从服务器进行独立调用很重要,尤其是当您将他们的 facebook 用户 ID 存储在数据库或其他东西中时。这样,您就知道它是否有效。
首先,在 Facebook Javascript SDK 中调用FB.init函数后,您想通过 Javascript SDK 获取用户的访问令牌和 facebook 用户 id,如下所示:
FB.getLoginStatus(function (response)
{
if (response.status === 'connected')
{
var token = response.authResponse.accessToken;
var facebookUserID = response.authResponse.userID;
}
});
其次,一旦您获得了令牌和 facebook 用户 ID,您将希望将这些变量传递给您的服务器。如果您将 WCF 或其他形式的 Web 服务与JSON.NET一起使用,则可以创建如下方法:
[WebInvokeAttribute(BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[OperationContractAttribute]
public Stream AuthenticateFacebook(string facebookUserId, string token)
{
var json = new WebClient().DownloadString(string.Format("https://graph.facebook.com/me?access_token={0}", token));
JObject parsedJson = JObject.Parse(json);
//Ensure that there isn't a random Facebook server error
if (parsedJson["error"] != null)
{
throw new FaultException("Error parsing Facebook token.");
}
//Ensure the facebook user ID passed in via the client matches the one received from the server.
if (Convert.ToString(parsedJson["id"]) != facebookUserId)
{
throw new FaultException("Facebook login ids do not match. Something fishy is going on...");
}
//Now you know you have a valid facebook login id. Do your database stuff or whatever else here.
}
您现在已经验证了用户就是他们所说的那个人。