//Login button click event
protected void Btnlogin_click (object sender, EventArgs e) {//Get the value of the interface string UserName = Txtusername.tex t;//Username String Password = txtpassword.text;//password string checkcode = session["code"]. ToString ();//Check out the validation code string code = txtcheckcode.text;//from session to get the input verification code try {if (code != checkcode) {Clientscript.registerstartupscript (this.
GetType (), "", "Alert (' Authentication code Error! ')", true);
Return
else {if (Userinfologic.checkuser (UserName, Password))//Call method query whether the user exists {session["login_name"] = txtusername.text;//the user name into session Formsauthenticati
Onticket ticket = new FormsAuthenticationTicket (1, UserName, DateTime.Now, DateTime.Now.AddMinutes (), True, "");
String encryptticket = Formsauthentication.encrypt (ticket); HttpCookie cookie = new HttpCookie (FoRmsauthentication.formscookiename, Encryptticket);
RESPONSE.COOKIES.ADD (cookie); if (request.querystring["returnurl"] = = null) {Response.Redirect ("home.aspx") ;//Login successfully jump to main interface} else {Response.redire
CT (request.querystring["ReturnUrl"]); } else {//Login failed jump to login page clientscr Ipt. RegisterStartupScript (this.
GetType (), "", "alert (' Login failed! ')", true);
Response.Redirect ("Login.aspx"); '} ' catch (Exception) {}}
configuration code in Web.config
<authentication mode= "Forms" >
<forms loginurl= "Login.aspx". Aspxauth ></forms>
<!--Specifies the URL that will be redirected to the login if no valid authentication Cookie is found. -->
</authentication>
<authorization>
<deny users= "?" ></deny>
<!--Add an authorization rule to the mapping of authorization rules that denies access to the resource. -->
<!--<allow users= "?"/>
adds a rule to the mapping of authorization rules that allows access to resources. -->
Create a new Global.asax
protected void Application_AuthenticateRequest (object sender, EventArgs e)
{
string cookiename = formsauthentication.formscookiename;//gets the name of the cookie from the validation ticket.
HttpCookie Authcookie = context.request.cookies[cookiename];
if (null = = Authcookie)
{return
;
}
Gets the validation ticket.
FormsAuthenticationTicket AuthTicket = Formsauthentication.decrypt (authcookie.value);
if (AuthTicket = = null)
{return
;
}
string[] roles = AuthTicket.UserData.Split (new char[] {', '});
FormsIdentity id = new FormsIdentity (AuthTicket);
System.Security.Principal.GenericPrincipal Principal = new System.Security.Principal.GenericPrincipal (ID, roles); Assigns the generated validation ticket information and role information to the current user.
Context.User = principal;
}