Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting HttpContext.Current.User

I am developing an asp.net mvc 3.0 application which has a simple authentication process. User fills a form which is sent to server by ajax call and gets response, but the problem here is that using the following method :

FormsAuthentication.SetAuthCookie(person.LoginName,false);

is not enough to fill 'HttpContext.Current.User' and it needs the below method to be run :

FormsAuthentication.RedirectFromLoginPage("...");

Problem here is that as i mentioned, the loggin form uses an ajax form, and get responses with json, so redirecting is not possible.

How could I fill 'HttpContext.Current.User' ?

Thanks.

Update :

Here is register method :

 [HttpPost]
        public ActionResult Register(Person person)
        {
            var q = da.Persons.Where(x => x.LoginName == person.LoginName.ToLower()).FirstOrDefault();

            if (q != null)
            {
                ModelState.AddModelError("", "Username is repettive, try other one");

                return Json(new object[] { false, this.RenderPartialViewToString("RegisterControl", person) });
            }
            else
            {
                if (person.LoginName.ToLower() == "admin")
                {
                    person.IsAdmin = true;
                    person.IsActive = true;
                }

                da.Persons.Add(person);

                da.SaveChanges();

                FormsAuthentication.SetAuthCookie(person.LoginName,false);
return Json(new object[] { true, "You have registered successfully!" });

}

}
like image 890
Babak Fakhriloo Avatar asked Jan 02 '12 18:01

Babak Fakhriloo


1 Answers

FormsAuthentication doesn't support immediate setting of user's identity, but you should be able to fake it by something like this:

HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
            new System.Security.Principal.GenericIdentity(person.LoginName), 
            new string[] { /* fill roles if any */ } );
like image 109
Lukáš Novotný Avatar answered Sep 27 '22 15:09

Lukáš Novotný