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 NET MVC download ZIP file
- Can i use mvc controllers in an asp net razor project type?
- Saving values of html table to database in ASP NET MVC and JQUERY/AJAX
- Need help retrieving dynamic values from checkboxes and turning the values into a list. ASP NET MVC
- ASP NET MVC 4 Razor Views Precompilation taking an insane amount of time
- How to add specific user to table when you have many in one List in asp net core mvc
- Loading Static Files from Controller ASP Net Core MVC
- ASP NET Core MVC Models / Foreign Key Assignment
- Cascade Dropdown in ASP Net Core 3.1 MVC
- How to run Html and Url helpers when use Html.Raw - ASP NET MVC
- Ajax request body from view to controller is empty in ASP NET Core MVC 3
- How to Use Rotativa Asp Net Core mvc in linux
- Object deserialization fails POST in Asp Net Core MVC Controller
- ASP Net MVC pagedlistpager without style
- ASP-PAGE not redirecting. ASP NET CORE MVC 3.1
- Consuming external Restful Web API with ASP Dot net MVC
- ASP NET MVC 5: Any way to avoid/ intercept back browser button?
- Telerik Reporting Using ASP NET MVC
- how to fix the link to the pictures in asp net mvc
- Persisting display data on Form Submission failure in Asp Net MVC
- Filling a combobox in asp net core mvc in razor view
- asp net mvc post gives empty viewmodel
- Extract all data from request payload to get them in Controller arguments C# Asp Net mvc
- how can use a custom method in controller in asp net mvc
- Activate/Deactivate user in user management system with asp net mvc
- ASP net mvc site.css keeps showing even when not referenced
- ASP NET MVC Include double my view
- Security error in ASP NET shared account
- Implementing filters for a SQL table display on a view in ASP.NET MVC (C#) and LINQ-to-SQL?
- ASP Net Core decimal input with period turns into zero
- Sort ObservableCollection with data from Firebase - Xamarin Firebase
- Declare a var of type Stripe charge create outside try catch
- How to read columns header in tab delimited text file C#
- Rendering in IE with fullcalendar
- How to handle back button for only on a certain page?
- Version exception error when connect to database using C# and SQL Server 2014
- adding multiple reactions to embed
- Running an executable under Scheduled Task with web access
- Why does the last element instantiated on a layout group appear as first and wrong?
- Trying to put a Html string to the WebView in Xamarin
- Roslyn, can not get provider to update solution after codefix
- WebBrowser scroll control
- Unable to compile repository downloaded from server
- Unity, c# how to get value of dictionary if the value is a list
- Dynamics AX 2012 AIF QueryService through C# - Relations and JoinMode usage between multiple tables
- Javascript / Validation for input
- How to give In-Air Momentum to a CharacterController-Based Player in Unity?
- Improve WPF Application Perceived Cold Startup Performance Using Splash Screen
- how to place datagrid column at the end of the datagrid row in wpf?
- XAML - Dynamic creation of different GridViews from only a Source