0

I'm setting up my first MVC site and I just implemented a security controller and views.

However what I don't understand is how I can persist the logged in user data across my controllers.

For example the user logs in with email/password. I can then verify that the email and passwords match and I do the following:

FormsAuthentication.SetAuthCookie(userLogin.UserName, false);
return View("../Home/Index");

Now say for example I want in the Index view to present data that only a user can see.

I have a table setup but it's based on the user_id.

Can I either save the user_id when they login or is there something already available to me to access their email(user)? (I could then look up the id via the email if necessary)

My MVC is setup for Forms authentication:

<authentication mode="Forms">
  <forms loginUrl="~/Security/Login" timeout="2880" />
</authentication>

and I decorated the controllers with the "[Authorize]" annotation.

John Doe
  • 3,053
  • 17
  • 48
  • 75

2 Answers2

3
FormsAuthentication.SetAuthCookie(userLogin.UserName, false);

Above code just sets authentication ticket inside cookie.

Once authenticated user sends a request, you still need to retrieve auth ticket from cookie, and create a Principal object.

Global.asax.cs

void Application_AuthenticateRequest(object sender, EventArgs e)
{
   HttpCookie decryptedCookie = 
      Context.Request.Cookies[FormsAuthentication.FormsCookieName];

   FormsAuthenticationTicket ticket = 
      FormsAuthentication.Decrypt(decryptedCookie.Value);

   var identity = new GenericIdentity(ticket.Name);
   var principal = new GenericPrincipal(identity, null);

   HttpContext.Current.User = principal;
   Thread.CurrentPrincipal =HttpContext.Current.User;
}

Usage

if (User.Identity.IsAuthenticated) {
   var username = User.Identity.Name;
}
Win
  • 61,100
  • 13
  • 102
  • 181
1

You can access the current user (username) in all controllers via

HttpContext.Request.RequestContext.HttpContext.User.Identity.Name

To find out any other information, you will normally need to query the database based on the username

ste-fu
  • 6,879
  • 3
  • 27
  • 46
  • I don't see HttpContext.Current. However this worked: HttpContext.Request.RequestContext.HttpContext.User.Identity.Name; I am using MVC5 if that matters. – John Doe Aug 16 '16 at 12:53
  • Sorry - edited - more info about it here https://stackoverflow.com/questions/785413/difference-between-httpcontext-current-and-controller-context-in-mvc-asp-net – ste-fu Aug 16 '16 at 12:58