in my asp.net mvc project i added facebook authentication to my project. I also save the facebook users in my database too. I have default asp.net authentication system for my site. When a facebook user give permission to my facebook application i get facebook user information like name,id and sa开发者_运维知识库ve them to my User table in my database, also give them a new guid for Id column. Then set them authenticated like below
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 make persistent cookie false because i dont know when they will logout from facebook.
When user comes again to my site (he also login facebook), i want him to be authenticated. But how can i do that ?
I am trying to set HttpContext.Current.User but i am not sure that i am on the right way, help me about this situation.
I am trying this.
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");
}
You will need to do FormsAuthentication.SetAuthCookie again when your app identifies the facebook user.
FacebookApp app = new FacebookApp();
if (app.Session != null)
{
FormsAuthentication.SetAuthCookie(app.Session.Username /*Or wherever you get it*/, false);
return View("AuthBox");
}
You cannot set HttpContext.User manually.
精彩评论