.NET MVC 4 Automatic Login after Registration

Recently, I’ve started working on my first MVC 4 project. The project required authentication system in place with the ability for users to register new accounts. Now, the basic Internet Template that comes with MVC 4 is enough to get you started. It provides basic Login and Register screens along with controllers. I’ve also added e-mail confirmation, thanks to spot on post by Kevin Junghans.
WebSecurity does most of the heavy lifting by generating a confirmation token we can append to a link in our email, stores it in the database along the UserName and then can be used to validate it and activate account. The part I needed to figure out was how to login a user using only confirmation token, so that clicking on a link in his confirmation e-mail would actually log him in, instead of being redirected to a login screen. It looks like “FormsAuthentication.SetAuthCookie(userName, true);” does the trick:

        [AllowAnonymous]
        public ActionResult RegisterConfirmation(string Id)
        {
            if (WebSecurity.ConfirmAccount(Id))
            {
                using (var db = new UsersContext())
                {
					// Use ConfirmationToken to figure out UserId, then use that to get UserName.
                    int userId = db.Memberships.Single(m => m.ConfirmationToken == Id).UserId;
                    string userName = db.UserProfiles.Single(u => u.UserId == userId).UserName;

					// Authenticate user.
                    FormsAuthentication.SetAuthCookie(userName, true);
                }
                return RedirectToAction("Index", "Home");
            }
            return View("ConfirmationFailure");
        }
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a comment