2010-11-07 51 views
0

我爲我的項目添加了Facebook身份驗證。我也將facebook用戶保存在我的數據庫中。我有我的網站默認的asp.net身份驗證系統。 當Facebook用戶給我的Facebook應用程序的權限時,我得到了像用戶名,ID這樣的Facebook用戶信息,並將它們保存到我的數據庫中的用戶表中,同時爲它們提供了一個新的Id列的GUID。然後將他們認證像下面Asp.net在我的asp.net mvc項目中手動驗證用戶代碼

public ActionResult FbInit() 
    { 
     FacebookApp app = new FacebookApp(); 

     if (app.Session != null) 
     { 
      dynamic parameters = new ExpandoObject(); 
      parameters.fields = "id,name"; 
      dynamic result = app.Api("me", parameters); 

      string id = result.id; 
      string name = result.name; 

      using (TestDbEntities context = new TestDbEntities()) 
      { 
       AuthTestAjax.Models.User newUser; 
       if (null == (newUser = context.Users.Where(p => p.FbId == id).FirstOrDefault())) 
       { 
        newUser = new User(); 
        newUser.Id = Guid.NewGuid(); 
        newUser.Name = name; 
        newUser.FbId = id; 
        context.AddToUsers(newUser); 
        context.SaveChanges(); 
       } 

       System.Web.Security.FormsAuthentication.SetAuthCookie(newUser.Id.ToString(), false); 
      } 

     } 


     return Json(""); 
    } 

-I做出永久性的Cookie假的,因爲我不知道他們什麼時候會從Facebook註銷。

當用戶再次來到我的網站(他也登錄Facebook),我希望他被認證。但我該怎麼做?

我想設置HttpContext.Current.User,但我不知道我在正確的方式,幫助我瞭解這種情況。

我正在試着這個。

 public ActionResult AuthBox() 
    { 
     if (HttpContext.User.Identity.IsAuthenticated) 
      return View("AuthBox"); 

     FacebookApp app = new FacebookApp(); 

     if (app.Session != null) 
     { 
      HttpContext.User // <== Can I set this here to authenticate user? 
      return View("AuthBox"); 
     } 

     return View("AnonyBox"); 
    } 

回答

1

當您的應用程序識別Facebook用戶時,您需要再次執行FormsAuthentication.SetAuthCookie。

 FacebookApp app = new FacebookApp(); 

     if (app.Session != null) 
     { 
      FormsAuthentication.SetAuthCookie(app.Session.Username /*Or wherever you get it*/, false); 
      return View("AuthBox"); 
     } 

您不能手動設置HttpContext.User。

+0

FormsAuthentication.SetAuthCookie對我來說不夠用,因爲第二個請求用戶被驗證(因爲auth cookie在第一個請求響應中發送他),所以我需要他在第一個請求時進行驗證。 – Yucel 2010-11-08 12:49:56

+0

啊,我不太清楚你將如何去做。 – Chev 2010-11-08 17:46:40