FormsAuthentication
FormsAuthentication class from System.Web.Security is used to authenticate a user whether login or not. FormsAuthentication class has many functions to check the user login and it's very easy to implement. Follow the code given below
Views
<h2>Login</h2>
<form method="post">
<input type="text" name="UserName" placeholder="User Name" required /><br /><br />
<input type="password" name="Password" placeholder="Password" required /><br /><br />
<input type="submit" value="Login" />
@if
(Request.QueryString["msg"] != null)
{
<br /><br />
<span style="color:red">@Request.QueryString["msg"]</span>
}
</form>
Admin
<h2>Admin
Dashboard</h2><hr />
Login Controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(LoginModel data)
{
if (data.UserName == "admin" && data.Password == "123")
{
System.Web.Security.FormsAuthentication.SetAuthCookie(data.UserName,
true);
return RedirectToAction("index", "admin");
}
else
return RedirectToAction("index", "login", new { msg = "Invalid Username or Password" });
}
Admin Controller
public ActionResult Index()
{
return View();
}
Logoff
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
Session.RemoveAll();
return RedirectToAction("Index", "portal");
}
Web.config
<system.web>
<authentication mode="Forms">
<forms loginUrl="login/index" timeout="2"></forms>
</authentication>
<authorization>
<allow users="?"></allow>
</authorization>
</system.web>
No comments:
Post a Comment