Recently I am working on an MVC 4 Web application project in which I need to implement the remember me feature on my website. I have found 2 solutions to this problem. I’m sharing my Solution with all of you.
We are going to implement a remember me functionality on the login page of our asp.net MVC project. and the first way is to do that is using the FormsAuthentication.SetAuthCookie function i.e using the Forms authentication mode.
We can also do that by creating cookies but just I want to let you know that
If You want make secure web application then should never store the user’s credentials in a cookie. It is un-secure. ASP.Net MVC already gives this functionality securely with Forms Authentication and ASP Membership Providers if you are using the Membership implementation.
You should take the advantage of that. When creating a default Asp .NET MVC project, Visual will include the basic authentication setup and project structure for us. you can use that setup for implementing the remember me feature.
In this Part, I will Explain to you Following Points:-
- How to implement remember me in Login page in MVC 4 razor?
- Remember me with login and logout in asp.net mvc
- How to implement keep me logged in asp.net mvc
- Formsauthentication setauthcookie in asp net
Using enable forms authentication
Create Database table for user login

public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
Create an Empty Mvc Porject for Login
Create Controller,add action method views
ManageAccount
.csusing RememberMe.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace RememberMe.Controllers
{
public class ManageAccountController : Controller
{
// GET: ManageAccount
public ActionResult Login()
{
return View();
}
// GET: ManageAccount
[HttpPost]
[AllowAnonymous]
public ActionResult Login(LoginViewModel model)
{
DummyDbEntities db = new DummyDbEntities();
string strresponse = string.Empty;
var user = db.Users.Where(a => a.Email == model.Email && a.Password == model.Password).FirstOrDefault();
if (user != null)
{
//user active
if (user.UserStatus == 1)
{
FormsAuthentication.SetAuthCookie(user.Email, model.RememberMe);
return RedirectToAction("UserProfile");
}
else
{
strresponse = "Your Account has not been activated.Please connect to admin";
}
}
else
{
strresponse = "Username or password is incorrect.Please try again!";
}
ViewBag.Message = strresponse;
return View();
}
// GET: ManageAccount/UserProfile
public ActionResult UserProfile()
{
return View();
}
[HttpPost]
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login");
}
}
}
Login.cshtml
@using RememberMe.Models
@model LoginViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="container body-content">
<div class="row">
<div class="col-md-8">
<section id="loginForm">
@using (Html.BeginForm("Login", "ManageAccount", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<h4>Use a local account to log in.</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Log in" class="btn btn-default" />
</div>
</div>
}
</section>
</div>
</div>
<hr />
</div>
@if (@ViewBag.Message != null)
{
<script type="text/javascript">
$(function () {
alert("@ViewBag.Message")
});
</script>
}
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@*@RenderSection("scripts", required: false)*@
</body>
</html>
UserProfile.cshtml
@using RememberMe.Models
@model LoginViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="container body-content">
<div class="row">
<div class="col-md-8">
<div>
@if (Request.IsAuthenticated)
{
<strong>Welcome @Html.Encode(User.Identity.Name)</strong>
using (Html.BeginForm("Logout", "ManageAccount", FormMethod.Post))
{
<a href="javascript:;" onclick="document.forms[0].submit();">Logout</a>
}
}
else
{
<a href="@Url.Action("","")" class="navbar-brand">Login</a>
}
</div>
</div>
</div>
<hr />
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
</body>
</html>
Step:4
set forms in authentication Web.Config
Add below line in web.config
<authentication mode="Forms">
<forms defaultUrl="/ManageAccount/login" loginUrl="/ManageAccount/login" slidingExpiration="true" timeout="2880"></forms>
</authentication>
if below line present in the config file then remove
<remove name="FormsAuthentication" />
Secured way provided by Microsoft,using ASP Membership Providers
- Create an default Mvc Porject with template
- It will create the basic template for you with
login ,registration,remember me feature. - Open acccount you can able see the all feature
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
Profile page
@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
The post Implementing “Remember Me” Feature in ASP.NET MVC appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- ASP dot net mvc - Add item to list not working, It does nothing
- How to get Identity Server 4's access_token in ASP Net 4.7 MVC Application
- How to implement Localization ASP net CORE MVC
- ASP NET MVC Core 2 Roles without database
- Issue with remember me in asp mvc membership
- Asp Net MVC Role Security
- compiler cannot find @model MembershipUserCollection in a view - Asp Net MVC 4 Application
- ASP NET MVC Validation Security Issue
- System.OutOfMemoryException asp net MVC
- asp net mvc default image display
- ASP NET CORE MVC My cookie is null, but it doesn't seem to be
- How to display Cshtml from Model property? ASP NET Core MVC
- Asp Net Mvc Routing without action on multiple Controllers
- Why iis return 403 error code with asp net mvc controller file stream
- Add role to user in Simple Membership ASP NET MVC 4
- ASP NET MVC 5: RedirectToAction stops to work all of a sudden
- DrawString with highlighted text in my asp net program using mvc
- ASP Net Core MVC Ajax Post
- ASP MVC 5 How to read object from request with the help of JSON NET
- Custom extension helper in asp net mvc that return partial view
- Error related to global.asax when combine MVC inside compiled asp net web form
- Add images dynamicaly asp net mvc 4
- Leafllet integration with ASP .NET MVC
- Display label on each bar chart in ASP .NET MVC 5 Chart
- Different URL's to the same controller ASP MVC Core
- ASP .NET core mvc & Microsoft Graph API
- How Do I Get Firebase IssuerSigningKey In Asp net Core 2
- Mock HttpPostedFileBase ASP MVC
- MVC Core ASP DatePicker not showing value when changing local PC DateFormat
- Entity Framework / ASP net core 2.0 - add migration working for some context but not for others
- Where to put global exception handler in Gtk# application?
- Performance of adding and removing values from HashSet<T> versus checking a flag in a Dictionary<T, bool>
- How to change bar chart value on each bar to custom value?
- How to do validation for a mandatory field without using Binding Path
- Default aspx cannot access class in other project
- NLog AzureAppendBlob not logging
- ComboBox behaving in a not expected way
- How can I make order irrelevant when calling fluent methods of inherited objects?
- Hide/Unhide Rows in Excel in VSTO application C#
- How to tear down Selenium (3.8) and close IE browser window?
- Why are two columns being created for a foreign key?
- Unity C# bool resetting to false
- Base class (Domain Model) conversion to derived class (View Model)
- Parent-Child Matrix Chaining/Order Hierarchy
- Using the Repository pattern - where is acceptable to use LINQ filtering?
- Why do I need I need to implement IDisposable() on a child class
- Stored procedure fulltext search
- DSharpPlus How to create or set a discord channel to NSFW in C#
- Listening to Events in the calendar from more than one person using EWS API
- Difficult to replicate objects (object Customer) on the list?