This is for cshtml code
This is used for Forms Authentication Ticket.
This is used for RedirectToAction.
@model Models.LoginViewModel
@{
Layout = null;
}
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
Welcome to PCX
Not a member? @Html.ActionLink("Sign up now »", "SignUpForGuestUser", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })
Or
@Html.ActionLink("Forgot your password?", "ForgotPassword", null, new { @class = "forgot-pass" })
}
This is Login controller with contain HttpPost, AllowAnonymous and ValidateAntiForgeryToken attribute.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
// Encrypt the ticket and Create the cookie.
EncryptTicketCookies(model);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", Messages.InvalidUidPwd);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
This is used for user Authentication.
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}
This is used for Forms Authentication Ticket.
private static void EncryptTicketCookies(LoginViewModel model)
{
bool createPersistentCookie = false;
string UserData = GetUserData(model);
//// Create and tuck away the cookie
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddDays(1), createPersistentCookie, UserData);
//// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(authTicket);
////// Create the cookie.
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
System.Web.HttpContext.Current.Response.Cookies.Add(faCookie);
}
This is used for RedirectToAction.
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}