Following the implementation of Custom Membership Provider and Custom Role Provider, I think it is now time to design an Account Controller with all of the required actions to assist us in authenticating users.
We're going to make a controller now. Right-click the controllers folder> > Add >> Controller>> MVC 5 Controller - Empty>> Add. Name the controller “AccountController” in the following dialogue, then click on the Add to add controller successfully.

Figure: Choose “MVC5 Controller-Empty” from the above controller

Figure: Choose “MVC5 Controller-Empty” from the above controller
Example
using CustomAuthenticationMVC.CustomAuthentication;
using CustomAuthenticationMVC.DataAccess;
using CustomAuthenticationMVC.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace CustomAuthenticationMVC.Controllers
{
[AllowAnonymous]
public class AccountController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult Login(string ReturnUrl = "")
{
if (User.Identity.IsAuthenticated)
{
return LogOut();
}
ViewBag.ReturnUrl = ReturnUrl;
return View();
}
[HttpPost]
public ActionResult Login(LoginView loginView, string ReturnUrl = "")
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(loginView.UserName, loginView.Password))
{
var user = (CustomMembershipUser)Membership.GetUser(loginView.UserName, false);
if (user != null)
{
CustomSerializeModel userModel = new Models.CustomSerializeModel()
{
UserId = user.UserId,
FirstName = user.FirstName,
LastName = user.LastName,
RoleName = user.Roles.Select(r => r.RoleName).ToList()
};
string userData = JsonConvert.SerializeObject(userModel);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket
(
1, loginView.UserName, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData
);
string enTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie("Cookie1", enTicket);
Response.Cookies.Add(faCookie);
}
if (Url.IsLocalUrl(ReturnUrl))
{
return Redirect(ReturnUrl);
}
else
{
return RedirectToAction("Index");
}
}
}
ModelState.AddModelError("", "Something Wrong : Username or Password invalid ^_^ ");
return View(loginView);
}
[HttpGet]
public ActionResult Registration()
{
return View();
}
[HttpPost]
public ActionResult Registration(RegistrationView registrationView)
{
bool statusRegistration = false;
string messageRegistration = string.Empty;
if (ModelState.IsValid)
{
string userName = Membership.GetUserNameByEmail(registrationView.Email);
if (!string.IsNullOrEmpty(userName))
{
ModelState.AddModelError("Warning Email", "Sorry: Email already Exists");
return View(registrationView);
}
//Save User Data
using (AuthenticationDB dbContext = new AuthenticationDB())
{
var user = new User()
{
Username = registrationView.Username,
FirstName = registrationView.FirstName,
LastName = registrationView.LastName,
Email = registrationView.Email,
Password = registrationView.Password,
ActivationCode = Guid.NewGuid(),
};
dbContext.Users.Add(user);
dbContext.SaveChanges();
}
VerificationEmail(registrationView.Email, registrationView.ActivationCode.ToString());
messageRegistration = "Your account has been created successfully. ^_^";
statusRegistration = true;
}
else
{
messageRegistration = "Something Wrong!";
}
ViewBag.Message = messageRegistration;
ViewBag.Status = statusRegistration;
return View(registrationView);
}
[HttpGet]
public ActionResult ActivationAccount(string id)
{
bool statusAccount = false;
using (AuthenticationDB dbContext = new DataAccess.AuthenticationDB())
{
var userAccount = dbContext.Users.Where(u => u.ActivationCode.ToString().Equals(id)).FirstOrDefault();
if (userAccount != null)
{
userAccount.IsActive = true;
dbContext.SaveChanges();
statusAccount = true;
}
else
{
ViewBag.Message = "Something Wrong !!";
}
}
ViewBag.Status = statusAccount;
return View();
}
public ActionResult LogOut()
{
HttpCookie cookie = new HttpCookie("Cookie1", "");
cookie.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie);
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account", null);
}
[NonAction]
public void VerificationEmail(string email, string activationCode)
{
var url = string.Format("/Account/ActivationAccount/{0}", activationCode);
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, url);
var fromEmail = new MailAddress("mehdi.rami2012@gmail.com", "Activation Account - AKKA");
var toEmail = new MailAddress(email);
var fromEmailPassword = "******************";
string subject = "Activation Account !";
string body = "
Please click on the following link in order to activate your account" + "
Activation Account ! ";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword)
};
using (var message = new MailMessage(fromEmail, toEmail)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
smtp.Send(message);
}
}
}
Account controller has three major actions, as you can see above.
- Check to see if the person who is going to create a new account has already been created. To do so, we'll use the CustomMembershipProvider's GetUserNameByEmail function.
- After that, we'll save user information.
- We must activate the user account by sending a verification email to the user, informing him that he must activate his account by clicking on the activation link.
- Login action takes a loginView model as a parameter, which has a username and password properties, and then uses the ValidateUser method from custom Membership to check user credentials. If user validation is true, the GetUser function is used to retrieve user data.
- Following that, we'll create an authentication ticket that will be encrypted using the term FormsAuthentication. Finally, we'll encrypt (authTicket) and create a faCookie object with our ticket's encrypted value as the value.
- The registration action is used to create a new account for a user. This action will do three things on a deep level:
- The LogOut action allows the user to log out of his or her session, as the name suggests.
We must now add account views for login, registration, and activation.
Example
@model CustomAuthenticationMVC.Models.LoginView
@{
ViewBag.Title = "Login";
}Login
@using (Html.BeginForm(null, null, new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post))
{
@Html.AntiForgeryToken()
}
@Html.ActionLink("Back to List", "Index")
Example
@model CustomAuthenticationMVC.Models.RegistrationView
@{
ViewBag.Title = "Registration";
}Registration
@if (ViewBag.Status != null && Convert.ToBoolean(ViewBag.Status))
{
if (ViewBag.Message != null)
{
Success! @ViewBag.Message
}
}
else
{
using (Html.BeginForm())
{
@Html.AntiForgeryToken()
if(ViewBag.Message != null)
{
Error! @ViewBag.Message
}
}
}
@Html.ActionLink("Login", "Login")
@section Scripts{
}
Example
@{
ViewBag.Title = "Activation Account ^_^";
}Activation Account
@if(ViewBag.Status != null && Convert.ToBoolean(ViewBag.Status))
{
Success! Your account has been activated successfully.
}
else
{
Error!@ViewBag.Message
}