Hi
How the below Forms Authentication code works - FormsAuthentication.SetAuthCookie(UserName,false);
[HttpPost]
public ActionResult Login(string UserName , string Password)
{
int res = dbUser.Admin_Login(UserName , Password);
if (res == 1)
{
TempData["msg"] = "login Successfully...!";
FormsAuthentication.SetAuthCookie(UserName,false);
return RedirectToAction("Index", "Location");
}
else
{
TempData["msg"] = "Admin id or Password is wrong...!";
}
return View();
}
************ Web.Config
Thanks
Sachin SinghPosted Jun 28, 2021, 11:44 AM
You need to understand multiple things.
1.HttpContext
HttpContext is the object created by the host (IIS) each time a request enters inside it, this is the main object that contains all the information about request and response.
2.Principal
HttpContext.Principal or Thread.Principal.
The principal is the object that contains the identity and roles associated with the request. we explicitly set it as
3. How does Authorize attribute works.
The Authorize attributes verify the request by analyzing this HttpContext.principal only. if it finds any Identity associated with it then it allows the request to enter otherwise denies.
4. when you configure the below code
then form's authentication module which is an Http Module of IIS activates, which also tells where to go if there is no Pricipal associated with the request, in your case it is Login method.
5. Browser's behaviour.
A browser sends the cookie along with the request if the request is for the same root URL, in your case localhost://portnumber, so the cookie associated with this domain will be sent on each request by the browser to the server.
6. the below codes creates a cookie with the identity UserName which resides in the browser, so with all next request browser sends this cookie to the server.
7. when the server (IIS) receives the cookie, the forms authentication module retrieves the information from it and sets the HttpContext.Principal.
8. finally, when the request hits the Authorize attribute, the attribute this time gets the principal so he allows it to enter into the method.