This article mainly introduces the authentication process of forms authentication in ASP. I think it is very good, and now share to everyone, but also to make a reference. Let's take a look at it with a little knitting.
Verification process
First, User Login
1. Verification form: Modelstate.isvalid
2. Verify user name and password: Verify by querying database
3. If the user name and password are correct, save the cookie on the client to save the user's login status: SetAuthCookie
1): Identify the user name and some necessary information from the database and save the additional information to UserData
2): Save the user name and UserData to the FormsAuthenticationTicket ticket
3): Encrypt the ticket Encrypt
4): Save the encrypted ticket to the cookie sent to the client
4. Skip to the Pre-logon page
5. If login fails, return to current view
Second, verify the login
1. Register the Postauthenticaterequest event function in global to parse the cookie data sent by the client.
1): Determine whether the user is logged in by HttpContext.Current.User.Identity (Formsidentity,isauthenticated,authenticationtype)
2): Parse value from HttpContext's request cookie, decrypt FormsAuthenticationTicket get UserData
2. Role Verification
1): Role validation can be performed by adding the authorize feature to the action
2): Role authentication in HttpContext.Current.User's IsInRole method (requires rewriting)
First, User Login
1. Set up Web. config
Set the redirect login page
<system.web><authentication mode= "Forms" > <forms name= "LoginName" loginurl= "/userinfo/login" cookieless= "UseCookies" path= "/" protection= "All" timeout= "></forms></authentication></" System.web>
Comment out
<modules> <!--<remove name= "FormsAuthentication"/>--></modules>
2, the login verification of the Controller
The controller adds a "[authorize]" modifier to the method to deny anonymity.
public class Userinfocontroller:controller//Controller {//Authentication filter [authorize] public ActionResult Index () { return View (); } }
Login in Controller
<summary>//user Login///</summary>//<returns></returns> public ActionResult login () {return View (); } [HttpPost] public actionresult login (loginmodels login) {if (modelstate.isvalid) {var model = db. Admininfo.firstordefault (A = A.adminaccount = = Login. AdminAccount && a.adminpwd = = login. ADMINPWD); if (model = NULL) {//Deposit note (when the user logs in to save information, if there is information to log in directly) var Dtomodel = new users {id = model.id, ADM INPWD = model. Adminpwd, Adminaccount=model. AdminAccount}; Call SetAuthCookie (Dtomodel); Get login address var returnUrl = request["ReturnUrl"]; Determine if the login address is not a null value if (!string. Isnullorwhitespace (RETURNURL)) {return Redirect (RETURNURL); } else {//return redirectitoaction return Redirect ("/home/index"); }} else {Modelstate.addmodelerror ("", "Account password is incorrect"); return View (login); }} else {Modelstate.addmodelerror ("", "inputIncorrect information "); return View (login); }
Make a cookie on your login account
<summary>////For login account///</summary>// <param name= "model" ></param> Public void SetAuthCookie (Users loginmodel) { ///1, convert object to JSON var userdata = Loginmodel.tojson (); 2. Create ticket FormsAuthenticationTicket FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (2, " Loginuser ", Datetime.now,datetime.now.adddays (1), false, UserData); Encrypt the note var tickeencrypt = formsauthentication.encrypt (ticket); Create a cookie that defines HttpCookie cookie = new HttpCookie (Formsauthentication.formscookiename, tickeencrypt); Cookies. HttpOnly = true; Cookies. Secure = Formsauthentication.requiressl; Cookies. Domain = Formsauthentication.cookiedomain; Cookies. Path = Formsauthentication.formscookiepath; Cookies. Expires = DateTime.Now.Add (formsauthentication.timeout); First remove the cookie in addition to the cookie Response.Cookies.Remove (formsauthentication.formscookiename); RESPONSE.COOKIES.ADD (cookie); }
3. Add model files in models
public class Loginmodels { //<summary>/////</summary> [DisplayName ("account")] [ Required (errormessage = "Account cannot be empty")] public string AdminAccount {get; set;} <summary>///password/// </summary> [DisplayName ("password")] [Required (errormessage = ") Password cannot be null ")] public string Adminpwd {get; set;}}
4, views in the Login code:
Copy the Code code as follows:
@using (Html.BeginForm ("Login", "account", new {ReturnUrl = Viewbag.returnurl}, FormMethod.Post, new {@class = "form-ho Rizontal ", role =" form "}))
5. Global Settings
protected void Application_AuthenticateRequest (object sender, EventArgs e) { //1, get HTTP request via sender // HttpApplication app = new HttpApplication ();//instantiation of HttpApplication app = sender as HttpApplication; 2. Get the HTTP context HttpContext contextual = app. Context; 3, according to Formsauthe, to obtain the cookie var cookie = context. Request.cookies[formsauthentication.formscookiename]; if (cookie = null) { //Gets the value of the cookie var ticket = formsauthentication.decrypt (cookie. Value); if (!string. Isnullorwhitespace (ticket. UserData)) { //turn a string class into a solid model var model = ticket. Userdata.toobject<admininfoviewmodel> (); var acount = model. AdminAccount; Get account context. User = new Myformsprincipal<admininfoviewmodel> (ticket, model); myformsprincipal.identity = new FormsIdentity (ticket); Myformsprincipal.userdata;}}}
6. Log Out
In the controller
<summary> ///Exit Login///</summary> public ActionResult loginout () { //delete ticket FormsAuthentication.SignOut (); Clear Cookie Response.cookies[formsauthentication.formscookiename]. Expires = DateTime.Now.AddDays ( -1); Response.Cookies.Remove (formsauthentication.formscookiename); Return redirecttoaction ("Index", "Home");
View Jump Link
@Html. ActionLink ("Safe exit", "Loginout", "Users")