3

I have an ASP.Net MVC 5 project that I recently migrated from MVC 4. I'm using FormsAuthentication with HTTPS and anonymous authentication, and setting a cookie using this:

FormsAuthentication.RedirectFromLoginPage(Username, false)

Authentication works, but the issue I'm having is getting the current user's name in my C# code. I can get at it fine in my view,

User.Identity.GetUserName()

but I can't get at it in the controller. HttpContext.CurrentUser doesn't exist, and this.User in the controller is always null. I've also tried requesting the cookie, but it fails.

Will I have to set the Identity myself when they sign on? I may need user rolls, but I could always query the database to get them.

In short, how can I get the current user's username in my controller in MVC 5? Thanks

Jooooosh
  • 331
  • 2
  • 4
  • 13
  • Forms Authentication or Identity? They are two different things. – jamesSampica Nov 20 '14 at 20:53
  • I'm using forms authentication, not identity. I figured identity was something you could use to store user info, but I guess not. – Jooooosh Nov 20 '14 at 20:55
  • This answer seemed to do the trick. You'll have to import `WebMatrix.WebData;` as well. If the user isn't authenticated it returns an empty string. http://stackoverflow.com/a/17254386/4051272 – Jooooosh Nov 20 '14 at 21:09
  • 2
    Shouldn't you be calling FormsAuthentication.SetAuthCookie(Username, false) instead? That creates the cookie and usually allows using User.Identity.Name later on. – Christian Droulers Nov 20 '14 at 22:04
  • I read somewhere `RedirectFromLoginPage` sets a cookie for you, but I checked on another controller and can get at `User.Identity` now. My problem was that I was posting to the home controller, then calling another controller's method like this `(new MyController()).MyMethod(myModel);`. Time to change that lol. Thanks for bringing that up, I never woulda figured that out. – Jooooosh Nov 21 '14 at 14:16
  • The called controller can get at User.Identity when using RedirectToAction and RedirectToActionPermanent. The only issue some people might have is that you can only pass one parameter, although I didn't have this issue. Here's the syntax, since I had some issues with it. `RedirectToAction("MyMethod", "MyController, myModel)`. Not `RedirectToAction("MyMethod", "MyController, new { arg = myModel })` – Jooooosh Nov 21 '14 at 15:17

1 Answers1

8
string cookieName = FormsAuthentication.FormsCookieName; //Find cookie name
HttpCookie authCookie = HttpContext.Request.Cookies[cookieName]; //Get the cookie by it's name
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value); //Decrypt it
string UserName = ticket.Name; //You have the UserName!