I have made a website with a page that includes a razor form. The user can login on this form and then redirects to a different page. The logging in (and logging out) works with formsauthentication succesfully. However, I can't seem to use HttpContext.Current.User.Identity.Name to retrieve the stored username (in the formsauthentication cookie). It returns an empty string "".
I am using MVC 5 and ASP 4.5 with no standard membership or role providers.
Login:
[HttpPost]
public ActionResult Login(User user)
{
if (ModelState.IsValid)
{
bool authenticated = userscontroller.isAuthorized(user.Email, user.Password);
if (authenticated)
{
if (userscontroller.isAuthenticated())
{
userscontroller.deAuthenticateUser();
}
userscontroller.authenticateUser(user);
return Redirect(Url.Action("Index", "Home"));
}
}
}
Authenticating the user:
public void authenticateUser(User user)
{
FormsAuthentication.SetAuthCookie(user.Username, false);
}
Then getting the name of the user:
public User userFromCookie()
{
if (isAuthenticated())
{
return getUserByUsername(HttpContext.Current.User.Identity.Name);
}
else { return null; }
}
isauthenticated()
public bool isAuthenticated()
{
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
return true;
}
else
{
return false;
}
}
Webconfig:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<authorization > <deny users="?"/> </authorization>
So the identity.name returns "".
Help is appreciated!
Possible reasons it does not work.
this.User.Identity.NameHere is a fully working example I created for you. This whole thing works, the only dependency is on a Newtonsoft library but you could remove that and put anything you want in the user data.
Here is the user controller
Here are the views. View Login.cshtml
View ShowUserName.cshtml
web.config section Note that the key was generated from some web site that came up in a google search. You should probably look into getting your own and with the correct encryption types as the site I used was somewhat dated.