在我看来,实现 Facebook 登录的最佳方法是在服务器端执行所有功能。使用诸如 Hammock 之类的 REST 库,您可以实现这一点。
这是一篇关于如何实现的非常有用的文章:http ://www2.suddenelfilio.net/2010/09/08/connect-to-facebook-using-asp-net-facebook-graph-api-hammock/
除了该链接之外,这里还有一些代码可以为您指明正确的方向:
登录页面
使用以下单击事件将 ASP.NET 按钮添加到此登录页面:
protected void FacebookLogin_Click(object sender, EventArgs e)
{
string fbOuthUrl = "https://graph.facebook.com/oauth/authorize?client_id=<client-id>&redirect_uri=<callback-page-url>&scope=email,publish_actions";
Response.Redirect(fbOuthUrl);
}
回调页面
正如您在按钮单击事件中看到的那样,redirect_uri
将指向我们的回调页面。此回调页面将执行所有功能以获取访问令牌和您需要执行的任何其他登录作业:
public partial class FBLoginCallback : System.Web.UI.Page
{
private string AccessToken;
protected void Page_Load(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(Request["code"]) && !Page.IsPostBack)
{
FacebookCallback();
}
}
private void FacebookCallback()
{
var client = new RestClient { Authority = "https://graph.facebook.com/oauth/" };
var request = new RestRequest { Path = "access_token" };
request.AddParameter("client_id", ConfigurationManager.AppSettings["facebook.appid"]);
request.AddParameter("redirect_uri", ConfigurationManager.AppSettings["facebook.login.callbackurl"]);
request.AddParameter("client_secret", ConfigurationManager.AppSettings["facebook.appsecret"]);
request.AddParameter("code", Request["code"]);
RestResponse response = client.Request(request);
// A little helper to parse the querystrings.
StringDictionary result = QueryStringHelper.ParseQueryString(response.Content);
AccessToken = result["access_token"];
SetUserInformation(AccessToken);
}
private void SetUserInformation(string sToken)
{
var client = new RestClient { Authority = "https://graph.facebook.com/" };
var request = new RestRequest { Path = "me" };
request.AddParameter("access_token", sToken); //Make use of the access token
RestResponse response = client.Request(request);
JavaScriptSerializer ser = new JavaScriptSerializer();
var parsedResult = ser.Deserialize<Facebook>(response.Content); //parsedResult will contain basic FB User info
//Redirect to the necessary page
Response.Redirect("/Default.aspx");
}
}
注意:这将需要使用 Hammock REST 库,正如我在文章开头所指出的那样。
我希望这有帮助。