我正在 ASP.NET MVC 3 中构建一个应用程序,我在其中实现了表单例份验证。
我还想为用户提供使用他们的 Facebook 帐户(以及将来可能的其他社交帐户)注册/登录的选项。
我正在使用 C# Facebook SDK
我已经成功实现了 facebook 登录工作流程。现在我的问题是,如何处理混合使用 Forms 和 Facebook Auth?我似乎找不到任何足够的例子来说明如何实现这一点。
关于我的 facebook 实现,我请求用户允许我将存储在我的数据库中的不会过期的 Auth Token。
最佳答案
为此你必须做这样的事情
- 创建一个实现 IIdentity 的自定义类 (CurrentIdentity)。重写此类的 .ToString() ,这样您就有了某种对象的序列化状态。我用过“|”分隔符。该字符串将存储在加密的 cookie 中。
创建 session cookie
public static HttpCookie AuthCookie(CurrentIdentity identity) { //Create the Authticket, store it in Cookie and redirect user back FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, identity.Name, DateTime.Now, DateTime.Now.AddHours(3), true, identity.ToString(), FormsAuthentication.FormsCookiePath); string encryptedTicket = FormsAuthentication.Encrypt(authTicket); HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); authCookie.Expires = authTicket.Expiration; return authCookie; }
将此 cookie 添加到响应中。
HttpResponse res = HttpContext.Current.Response; res.Cookies.Add(Helper.AuthCookie(identity)); res.Redirect(FormsAuthentication.GetRedirectUrl(identity.Name, true)); res.End();
现在在 Gloabl.asax 中,在 *Application_AuthenticateRequest* 中读取此 cookie 并填充您的 CurrentIdentity 对象,如下所示。
if (Request.IsAuthenticated == true) { // Extract the forms authentication cookie string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; if (null == authCookie) { // There is no authentication cookie. return; } FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch (Exception) { // Log exception details (omitted for simplicity) return; } if (null == authTicket) { // Cookie failed to decrypt. return; } // When the ticket was created, the UserData property was assigned a // pipe delimited string of role names. string[] userInfo = authTicket.UserData.Split('|'); // Create an Identity object FormsIdentity id = new FormsIdentity(authTicket); //Populate CurrentIdentity, from Serialized string CurrentIdentity currentIdentity = new CurrentIdentity(userInfo[0], userInfo[1], userInfo[2]); System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(currentIdentity, userInfo); Context.User = principal; }
这应该可以解决您的问题。我在我的 company's website 上实现了类似的东西.
关于c# - 在 ASP.NET MVC 中与 Facebook/其他身份验证一起实现表单例份验证的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8804308/