facebook与asp.net网站的集成
我已经实现了一个Facebook登录并注册到一个我正在开发的ASP.NET网站,但不确定是否有最好的流程欢迎任何评论/更正。我发现开发过程有点脱节。。。facebook为你提供了拼图的各个部分,但在我看来,这些部分是如何组合在一起的还不够。我是这样做的:- 母版页:-facebook与asp.net网站的集成,asp.net,facebook,login,registration,Asp.net,Facebook,Login,Registration,我已经实现了一个Facebook登录并注册到一个我正在开发的ASP.NET网站,但不确定是否有最好的流程欢迎任何评论/更正。我发现开发过程有点脱节。。。facebook为你提供了拼图的各个部分,但在我看来,这些部分是如何组合在一起的还不够。我是这样做的:- 母版页:- <!doctype html> <%--facebook namespace needed for xfbml ...--%> <html xmlns:fb="http://ogp.me/ns/fb#
<!doctype html>
<%--facebook namespace needed for xfbml ...--%>
<html xmlns:fb="http://ogp.me/ns/fb#">
如果找不到电子邮件,请重定向至RegistrationFacebook.aspx,通过Facebook注册插件提供注册
注册Facebook.aspx:-
<div id="facebook_registration" runat="server">
<iframe src="https://www.facebook.com/plugins/registration.php?
client_id=110835352327502&
redirect_uri=http://localhost/RegistrationFacebookBackend.aspx&
fields=
[
{'name':'name'},
{'name':'first_name'},
{'name':'last_name'},
{'name':'email'},
{'name':'password'},
{'name':'_business', 'description':'Do you work for ?', 'type':'select', 'options':{'':'I do not work for ','f5f064ad-0db4-42ce-ba86-e65e6d262768':'xxxxxxxx','534d6c7b-6c3a-4b7d-a41c-9e240c199f1d':'xxxxxxxx'}},
{'name':'network', 'description':'Please select your region', 'type':'select', 'options':{'a':'a','b':'b','c':'c','d':'d','e':'e','f':'f','g':'g','h':'h','i':'i','j':'j','k':'k','l':'l','96e9b78a-cc3b-4c6e-b4e4-bc0ba18184c1':'UK','521199a2-5847-4ec0-bca1-19052a110da8':'South Africa'}},
{'name':'public_profile', 'description':'Make my profile public so other users can see me', 'type':'checkbox', 'default':'checked'},
{'name':'newsletter', 'description':'Please send me the monthly Unite newsletter', 'type':'checkbox'},
{'name':'sponsor_email', 'description':'Please email me when someone sponsors me', 'type':'checkbox', 'default':'checked'},
{'name':'tandc', 'description':'I confirm that I have read and accepted the Terms and Conditions', 'type':'checkbox'}
]
"
scrolling="auto"
frameborder="no"
style="border:none"
allowTransparency="true"
width="100%"
height="530">
</iframe>
</div>
RegistrationFacebook.aspx中的注册插件发回RegistrationFacebookBackend.aspx,以向ASP.NET应用程序注册用户。这里主要关注的是facebook表单签名请求变量在页面加载中的解码以及成员资格和个人资料的创建。我们使用CachedMembershipProvider,但在这里仅替换普通的成员资格提供程序代码。(networkGUID只是我们应用程序的一部分,请忽略它:-
public partial class RegistrationFacebookBackend : System.Web.UI.Page
{
private UserService userService;
private MembershipUser newUser;
private string userName; private string email; private string password; private string firstname; private string lastname;
private string _business; private string network; private string location;
private bool newsletter; private bool sponsor_email;
//private Guid networkId;
#region public properties
public UserService UserService
{
get { return userService ?? (userService = new UserService()); }
}
public MembershipUser NewUser
{
get { return newUser ?? (newUser = Membership.GetUser(userName)); }
}
#endregion
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
//
}
else // Request with Facebook signed_request payload ... create the user
{
if (!string.IsNullOrEmpty(Request.Form["signed_request"]))
{
string payload = Request.Form["signed_request"].Split('.')[1];
var encoding = new UTF8Encoding();
var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
var json = encoding.GetString(base64JsonArray);
var o = JObject.Parse(json);
userName = o.SelectToken("registration.email").ToString().Replace("\"", "");
email = o.SelectToken("registration.email").ToString().Replace("\"", "");
password = o.SelectToken("registration.password").ToString().Replace("\"", "");
firstname = o.SelectToken("registration.first_name").ToString().Replace("\"", "");
lastname = o.SelectToken("registration.last_name").ToString().Replace("\"", "");
_business = o.SelectToken("registration._business").ToString().Replace("\"", "");
network = o.SelectToken("registration.network").ToString().Replace("\"", "");
location = o.SelectToken("user.country").ToString().Replace("\"", "");
newsletter = (o.SelectToken("registration.newsletter").ToString().Replace("\"","") == "checked") ? true : false;
sponsor_email = (o.SelectToken("registration.sponsor_email").ToString().Replace("\"","") == "checked") ? true : false;
MembershipCreateStatus createStatus;
CachedMembershipProvider cmp = new CachedMembershipProvider();
System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();
nvc.Add("providerName","AspNetSqlMembershipProvider");
cmp.Initialize("CachedMembershipProvider", nvc );
newUser = cmp.CreateUser(userName, password, email, null, null, true, Guid.NewGuid(), out createStatus);
switch (createStatus)
{
case MembershipCreateStatus.Success:
// set roles and create profile
SetUserProfile(true);
FormsAuthentication.SetAuthCookie(newUser.UserName, true);
Response.Redirect("RegistrationFacebook.aspx?facebook_result=Success");
break;
case MembershipCreateStatus.InvalidUserName:
Response.Redirect("RegistrationFacebook.aspx?facebook_result=InvalidUserName");
break;
case MembershipCreateStatus.DuplicateUserName:
Response.Redirect("RegistrationFacebook.aspx?facebook_result=DuplicateUserName");
break;
case MembershipCreateStatus.DuplicateEmail:
Response.Redirect("RegistrationFacebook.aspx?facebook_result=DuplicateEmail");
break;
case MembershipCreateStatus.InvalidEmail:
Response.Redirect("RegistrationFacebook.aspx?facebook_result=InvalidEmail");
break;
case MembershipCreateStatus.InvalidPassword:
Response.Redirect("RegistrationFacebook.aspx?facebook_result=InvalidPassword");
break;
default:
Response.Redirect("RegistrationFacebook.aspx?facebook_result=error_default");
break;
}
}
else // Request WITHOUT Facebook signed_request payload
{
}
}
}
/// <summary>
/// Gets the user profile.
/// </summary>
/// <param name="profileUserName">Name of the user.</param>
/// <returns></returns>
private Web.WebProfile GetUserProfile(string profileUserName)
{
ProfileBase wp = Web.WebProfile.Create(profileUserName);
return new Web.WebProfile(wp);
}
/// <summary>
/// Sets the user profile.
/// </summary>
private void SetUserProfile(bool createEvents)
{
if (newUser == null)
{
throw new ArgumentNullException("newUser");
}
//Control container = CreateUserWizard1.CreateUserStep.ContentTemplateContainer;
Web.WebProfile newProfile = GetUserProfile(NewUser.UserName);
newProfile.UserId = (Guid)NewUser.ProviderUserKey;
newProfile.FirstName = firstname;
newProfile.LastName = lastname;
newProfile.EmailAddress = email;
newProfile.NetworkId = NetworkGuid;
newProfile.FurtherInformationOptIn = true;
newProfile.Location = location;
newProfile.IsTemporary = false;
newProfile.OptInFavourites = false;
newProfile.OptInNewsletters = newsletter;
newProfile.OptInGiveTimeEvents = false;
newProfile.OptInFundraisers = sponsor_email;
newProfile.OptInNews = false;
newProfile.Save();
newProfile = new WebProfile(WebProfile.Create(NewUser.UserName));
UserService.CreateNewProfilePage(newProfile, false);
if (createEvents)
{
EventService ues = new EventService();
IEvent ue = ues.CreateEvent(EventType.Registration, newProfile.NetworkId, newProfile.UserId,
newProfile.UserId);
}
}
protected Guid NetworkGuid
{
get
{
Guid networkGuid;
if (Convertors.GuidTryParse(_business, out networkGuid) == true)
{
return networkGuid; // if they have selected a business that is the one to use
}
else if (Convertors.GuidTryParse(network, out networkGuid) == true)
{
return networkGuid; // otherwise use the region they have selected
}
else
{ //otherwise default to UK
Convertors.GuidTryParse("96e9b78a-cc3b-4c6e-b4e4-bc0ba18184c1", out networkGuid);
return networkGuid;
}
}
}
}
公共部分类注册FaceBookBackend:System.Web.UI.Page
{
私人用户服务;
私人会员用户newUser;
私有字符串用户名;私有字符串电子邮件;私有字符串密码;私有字符串名;私有字符串名;
私有字符串业务;私有字符串网络;私有字符串位置;
私人bool通讯;私人bool赞助商电子邮件;
//专用Guid网络ID;
#区域公共财产
公共用户服务用户服务
{
获取{return userService???(userService=new userService());}
}
公共成员身份用户NewUser
{
获取{return newUser???(newUser=Membership.GetUser(userName));}
}
#端区
///
///处理页面控件的加载事件。
///
///事件的来源。
///包含事件数据的实例。
受保护的无效页面加载(对象发送方、事件参数e)
{
如果(第IsPostBack页)
{
//
}
else//请求带有Facebook签名的请求负载…创建用户
{
if(!string.IsNullOrEmpty(Request.Form[“signed_Request”]))
{
string payload=Request.Form[“signed_Request”].Split('.')[1];
var encoding=新的UTF8Encoding();
var decodedJson=payload.Replace(“=”,string.Empty).Replace('-','+').Replace(''''-','/');
var base64JsonArray=Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length+(4-decodedJson.Length%4)%4'=);
var json=encoding.GetString(base64JsonArray);
var o=JObject.Parse(json);
userName=o.SelectToken(“registration.email”).ToString().Replace(“\”,”);
email=o.SelectToken(“registration.email”).ToString().Replace(“\”,”);
password=o.SelectToken(“registration.password”).ToString().Replace(“\”,”);
firstname=o.SelectToken(“registration.first\u name”).ToString().Replace(“\”,”);
lastname=o.SelectToken(“registration.last\u name”).ToString().Replace(“\”,”);
_business=o.SelectToken(“registration.\u business”).ToString()。替换(“\”,”);
network=o.SelectToken(“registration.network”).ToString().Replace(“\”,”);
location=o.SelectToken(“user.country”).ToString().Replace(“\”,”);
时事通讯=(o.SelectToken(“registration.newsletter”).ToString().Replace(“\”,“)==”checked”)?真:假;
赞助商电子邮件=(o.SelectToken(“registration.赞助商电子邮件”).ToString().Replace(“\”,“)==”checked”)?真:假;
成员资格createStatus createStatus;
CachedMembershipProvider cmp=新的CachedMembershipProvider();
System.Collections.Specialized.NameValueCollection nvc=新的System.Collections.Specialized.NameValueCollection();
添加(“providerName”、“AspNetSqlMembershipProvider”);
初始化(“CachedMembershipProvider”,nvc);
newUser=cmp.CreateUser(用户名、密码、电子邮件、null、null、true、Guid.NewGuid()、out createStatus);
开关(创建状态)
{
案例成员资格CreateStatus。成功:
//设置角色并创建配置文件
SetUserProfile(true);
FormsAuthentication.SetAuthCookie(newUser.UserName,true);
Response.Redirect(“RegistrationFacebook.aspx?facebook_result=Success”);
打破
案例成员资格CreateStatus.InvalidUserName:
Response.Redirect(“RegistrationFacebook.aspx?facebook_result=InvalidUserName”);
打破
案例成员资格CreateStatus.DuplicateUserName:
Response.Redirect(“RegistrationFacebook.aspx?facebook_result=DuplicateUserName”);
打破
案例成员资格CreateStatus.Duplicate电子邮件:
Response.Redirect(“RegistrationFacebook.aspx?facebook_result=DuplicateEmail”);
打破
案例成员资格CreateStatus.InvalidEmail:
Response.Redirect(“RegistrationFacebook.aspx?facebook_result=InvalidEmail”);
打破
案例成员资格CreateStatus.InvalidPassword:
Response.Redirect(“RegistrationFacebook.aspx?facebook_result=InvalidPassword”);
打破
违约:
重定向(“RegistrationFacebook.aspx?facebook_result=error_default”);
打破
}
}
else//没有Facebook签名的请求负载的请求
{
}
}
}
///
///得到
<div id="facebook_registration" runat="server">
<iframe src="https://www.facebook.com/plugins/registration.php?
client_id=110835352327502&
redirect_uri=http://localhost/RegistrationFacebookBackend.aspx&
fields=
[
{'name':'name'},
{'name':'first_name'},
{'name':'last_name'},
{'name':'email'},
{'name':'password'},
{'name':'_business', 'description':'Do you work for ?', 'type':'select', 'options':{'':'I do not work for ','f5f064ad-0db4-42ce-ba86-e65e6d262768':'xxxxxxxx','534d6c7b-6c3a-4b7d-a41c-9e240c199f1d':'xxxxxxxx'}},
{'name':'network', 'description':'Please select your region', 'type':'select', 'options':{'a':'a','b':'b','c':'c','d':'d','e':'e','f':'f','g':'g','h':'h','i':'i','j':'j','k':'k','l':'l','96e9b78a-cc3b-4c6e-b4e4-bc0ba18184c1':'UK','521199a2-5847-4ec0-bca1-19052a110da8':'South Africa'}},
{'name':'public_profile', 'description':'Make my profile public so other users can see me', 'type':'checkbox', 'default':'checked'},
{'name':'newsletter', 'description':'Please send me the monthly Unite newsletter', 'type':'checkbox'},
{'name':'sponsor_email', 'description':'Please email me when someone sponsors me', 'type':'checkbox', 'default':'checked'},
{'name':'tandc', 'description':'I confirm that I have read and accepted the Terms and Conditions', 'type':'checkbox'}
]
"
scrolling="auto"
frameborder="no"
style="border:none"
allowTransparency="true"
width="100%"
height="530">
</iframe>
</div>
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
// its a save of content in admin mode
}
else
{
// RegistrationFacebookBackend has redirected back here after creating the user
if (!String.IsNullOrEmpty(Request.QueryString["facebook_result"]))
{
switch (Request.QueryString["facebook_result"])
{
case "Success":
CreateAccountResultsSuccess.Text = "You have successfully registered with Unite and the Unite Facebook app!";
CreateAccountResultsSuccess.Visible = true;
facebook_registration.Visible = false;
break;
case "InvalidUserName":
CreateAccountResultsError.Text = Resources.Error_Registration_InvalidUserName;
CreateAccountResultsError.Visible = true;
break;
case "DuplicateUserName":
CreateAccountResultsError.Text = Resources.Error_Registration_DuplicateUserName;
CreateAccountResultsError.Visible = true;
break;
case "DuplicateEmail":
CreateAccountResultsError.Text = Resources.Error_Registration_DuplicateEmail;
CreateAccountResultsError.Visible = true;
break;
case "InvalidEmail":
CreateAccountResultsError.Text = Resources.Error_Registration_InvalidEmail;
CreateAccountResultsError.Visible = true;
break;
case "InvalidPassword":
CreateAccountResultsError.Text = Resources.Error_Registration_InvalidPassword;
CreateAccountResultsError.Visible = true;
break;
default:
CreateAccountResultsError.Visible = true;
CreateAccountResultsError.Text = Resources.Error_Registration_Default;
break;
}
}
}
}
}
public partial class RegistrationFacebookBackend : System.Web.UI.Page
{
private UserService userService;
private MembershipUser newUser;
private string userName; private string email; private string password; private string firstname; private string lastname;
private string _business; private string network; private string location;
private bool newsletter; private bool sponsor_email;
//private Guid networkId;
#region public properties
public UserService UserService
{
get { return userService ?? (userService = new UserService()); }
}
public MembershipUser NewUser
{
get { return newUser ?? (newUser = Membership.GetUser(userName)); }
}
#endregion
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
//
}
else // Request with Facebook signed_request payload ... create the user
{
if (!string.IsNullOrEmpty(Request.Form["signed_request"]))
{
string payload = Request.Form["signed_request"].Split('.')[1];
var encoding = new UTF8Encoding();
var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
var json = encoding.GetString(base64JsonArray);
var o = JObject.Parse(json);
userName = o.SelectToken("registration.email").ToString().Replace("\"", "");
email = o.SelectToken("registration.email").ToString().Replace("\"", "");
password = o.SelectToken("registration.password").ToString().Replace("\"", "");
firstname = o.SelectToken("registration.first_name").ToString().Replace("\"", "");
lastname = o.SelectToken("registration.last_name").ToString().Replace("\"", "");
_business = o.SelectToken("registration._business").ToString().Replace("\"", "");
network = o.SelectToken("registration.network").ToString().Replace("\"", "");
location = o.SelectToken("user.country").ToString().Replace("\"", "");
newsletter = (o.SelectToken("registration.newsletter").ToString().Replace("\"","") == "checked") ? true : false;
sponsor_email = (o.SelectToken("registration.sponsor_email").ToString().Replace("\"","") == "checked") ? true : false;
MembershipCreateStatus createStatus;
CachedMembershipProvider cmp = new CachedMembershipProvider();
System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();
nvc.Add("providerName","AspNetSqlMembershipProvider");
cmp.Initialize("CachedMembershipProvider", nvc );
newUser = cmp.CreateUser(userName, password, email, null, null, true, Guid.NewGuid(), out createStatus);
switch (createStatus)
{
case MembershipCreateStatus.Success:
// set roles and create profile
SetUserProfile(true);
FormsAuthentication.SetAuthCookie(newUser.UserName, true);
Response.Redirect("RegistrationFacebook.aspx?facebook_result=Success");
break;
case MembershipCreateStatus.InvalidUserName:
Response.Redirect("RegistrationFacebook.aspx?facebook_result=InvalidUserName");
break;
case MembershipCreateStatus.DuplicateUserName:
Response.Redirect("RegistrationFacebook.aspx?facebook_result=DuplicateUserName");
break;
case MembershipCreateStatus.DuplicateEmail:
Response.Redirect("RegistrationFacebook.aspx?facebook_result=DuplicateEmail");
break;
case MembershipCreateStatus.InvalidEmail:
Response.Redirect("RegistrationFacebook.aspx?facebook_result=InvalidEmail");
break;
case MembershipCreateStatus.InvalidPassword:
Response.Redirect("RegistrationFacebook.aspx?facebook_result=InvalidPassword");
break;
default:
Response.Redirect("RegistrationFacebook.aspx?facebook_result=error_default");
break;
}
}
else // Request WITHOUT Facebook signed_request payload
{
}
}
}
/// <summary>
/// Gets the user profile.
/// </summary>
/// <param name="profileUserName">Name of the user.</param>
/// <returns></returns>
private Web.WebProfile GetUserProfile(string profileUserName)
{
ProfileBase wp = Web.WebProfile.Create(profileUserName);
return new Web.WebProfile(wp);
}
/// <summary>
/// Sets the user profile.
/// </summary>
private void SetUserProfile(bool createEvents)
{
if (newUser == null)
{
throw new ArgumentNullException("newUser");
}
//Control container = CreateUserWizard1.CreateUserStep.ContentTemplateContainer;
Web.WebProfile newProfile = GetUserProfile(NewUser.UserName);
newProfile.UserId = (Guid)NewUser.ProviderUserKey;
newProfile.FirstName = firstname;
newProfile.LastName = lastname;
newProfile.EmailAddress = email;
newProfile.NetworkId = NetworkGuid;
newProfile.FurtherInformationOptIn = true;
newProfile.Location = location;
newProfile.IsTemporary = false;
newProfile.OptInFavourites = false;
newProfile.OptInNewsletters = newsletter;
newProfile.OptInGiveTimeEvents = false;
newProfile.OptInFundraisers = sponsor_email;
newProfile.OptInNews = false;
newProfile.Save();
newProfile = new WebProfile(WebProfile.Create(NewUser.UserName));
UserService.CreateNewProfilePage(newProfile, false);
if (createEvents)
{
EventService ues = new EventService();
IEvent ue = ues.CreateEvent(EventType.Registration, newProfile.NetworkId, newProfile.UserId,
newProfile.UserId);
}
}
protected Guid NetworkGuid
{
get
{
Guid networkGuid;
if (Convertors.GuidTryParse(_business, out networkGuid) == true)
{
return networkGuid; // if they have selected a business that is the one to use
}
else if (Convertors.GuidTryParse(network, out networkGuid) == true)
{
return networkGuid; // otherwise use the region they have selected
}
else
{ //otherwise default to UK
Convertors.GuidTryParse("96e9b78a-cc3b-4c6e-b4e4-bc0ba18184c1", out networkGuid);
return networkGuid;
}
}
}
}