Tuesday, May 28, 2013

how to set httpContext.User.Identity.Name, form authentication

My friend asked me how to set httpContext.User.Identity.Name, because he was getting the object is null, so to answer his questing i have shared the this piece of implementation, and sharing the same on this article.

Step 1 :
In your authentication method make sure you have added  FormsAuthentication.SetAuthCookie , which actually set the httpContext.User object, the following code shows how easily you can do that.

tbAdminUser adminUser = _AdminAcctService.Authenticate(model.UserName, model.Password);

            if (adminUser != null)
            {
                Session["AdminUser"] = adminUser;

              FormsAuthentication.SetAuthCookie(model.UserName, true);

                return RedirectToAction("Index", "JewelAdmin");
            }
            else
                ViewBag.ErrorMessage = "Username or password is incorrect";

Step 2:
Now before performing any task, to check if the user is authenticated or not you can check
httpContext.User.Identity.IsAuthenticated  or  if (httpContext.User.Identity.Name == null)

Step 3:
While logging out, make sure you have set the following line in your logout method
FormsAuthentication.SignOut(); this will clear off the cookie which was been set by SetAuthCookie, so the User Name will become null in your HttpContext object.

Namespace required using System.Web.Security;

No comments: