Facebook 使用OAuth 2.0。对用户进行身份验证的唯一方法是将用户发送到 Facebook 登录页面,然后使用他们的 OAuth 实现重定向回来。这实际上为您提供了用户特定的时间限制access_token。
它并不适合 MembershipProviders,尽管可以请求 offline_access permission,它允许您随时代表用户执行授权请求。用户必须同意这一点。 Facebook 的条款和条件是,您不能因为不同意扩展权限而拒绝用户访问您的网站,因此这再次打破了模式。
我并不是说这不可能,只是看起来不值得付出努力。您最好只使用没有成员资格的表单身份验证部分。基于 facebook access_token 设置 auth cookie 和验证 auth cookie。
要使用 Facebook 进行身份验证,请查看开源 .NET OAuth 库。我还写了一篇关于 Facebook 集成的文章,其中展示了一些集成技术(和观点)here。
更新根据您修改的问题:
使用表单身份验证 cookie 来存储您选择的唯一标识符(例如 Facebook 用户名)。您还可以将当前的access_token 存储在 cookie 中。
if (OAuth.ValidateUser(username, user_access_token))
{
// store the user access token to make it available on each request
string userData = user_access_token;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // ticket version
username, // authenticated username
DateTime.Now, // issueDate
DateTime.Now.AddMinutes(30), // expiryDate
isPersistent, // true to persist across browser sessions
userData, // can be used to store additional user data
FormsAuthentication.FormsCookiePath); // the path for the cookie
// Encrypt the ticket using the machine key
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
// Add the cookie to the request to save it
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket));
// Your redirect logic
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
}
然后覆盖身份验证请求以读取 cookie 并检索用户详细信息。
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookie[FormsAuthentication.FormsCookieName];
if(authCookie != null)
{
//Extract the forms authentication cookie
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
// If caching roles in userData field then extract
string user_access_token = authTicket.UserData;
// Create the IIdentity instance, maybe use a custom one
// possibly retrieve extra data from database or whatever here
IIdentity id = new FacebookIdentity( authTicket, user_access_token );
// Create the IPrinciple instance
IPrincipal principal = new GenericPrincipal(id, new string[]{});
// Set the context user
Context.User = principal;
}
}
然后在每个请求的代码中:
var username = Context.User.Identity.Username;
// implement as an extension method on IIdentity which types to
// FacebookIdentity to get user_access_token
var user_access_token = Context.User.Identity.Access_Token;