I want the benefits of form authentication in ASP.NET. I want it to persist the authorization for me and such, but there\'s one thing different about my situation; I want to au
I may be over simplifying this, but the way I read this is the following:
If the above is correct, you do not need a membership provider. The [Authorize] attribute simply looks that the forms authentication cookie to see if it has been set and is valid for the current lifetime of the cookie. This authentication cookie stores the username of the user and the expiration time of the cookie (and other stuff, but not important here).
Given that, you only need to set your web.config configuration element and have a method to set the authentication cookie.
Web.Config
Logon URL GET action
public ActionResult Logon(){
//if the user is logged in, send the to the home page
if(httpContext.User.Identity.IsAuthenticated_{
Return RedirectToAction("Index", "Home");
}
Return this.View(new LoginViewModel());
}
Logon URL POST action
[HttpPost]
public ActionResult Logon(LoginViewModel model){
//Check for model errors
if(!ModelState.IsValid()){
Return this.View(model);
}
//Validate against web service - return error if false
if(!CheckClientsWebService(model.UserName, model.Password)){
ModelState.AddModelError("","The username or password is invalid");
Return this.View(model);
}
//Manually set the authentication cookie
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
//Send them on to the home page, they now have a authorization cookie
Return RedirectToAction("Index", "Home");
}
Once you have called the .SetAuthCookie()
function, the user will now have an authentication ticket and calls to HttpContext.User.Identity.IsAuthenticated
will be true as long as the cookie has not expired and you can get the user name from HttpContext.User.Identity.Name