Protected void page_load (object sender, eventargs e)
{
If (request. cookies ["username"] = null)
{
Httpcookie mycookie = new httpcookie ("username ");
Mycookie. values. add ("prodid ","");
Mycookie. expires = datetime. now. adddays (1 );
Response. cookies. add (mycookie );
}
}
This is the cookie inserting code.
Public void addcookie (string cookievalue)
{
Httpcookie cookie = new httpcookie ("username ");
If (request. cookies ["username"]. values ["prodid"]! = "")
{
String myvalue = "";
Myvalue = request. cookies ["username"]. values ["prodid"]. tostring ();
Myvalue = cookievalue + "," + myvalue;
Cookie. values. add ("prodid", myvalue );
Cookie. expires = datetime. now. adddays (1 );
Response. cookies. add (cookie );
}
Else
{
Cookie. values. add ("prodid", cookievalue );
Cookie. expires = datetime. now. adddays (1 );
Response. cookies. add (cookie );
}
}
The last step is to delete the cookie.
Protected void button2_click (object sender, eventargs e)
{
Httpcookie mycookie = new httpcookie ("username ");
Mycookie. expires = datetime. now. adddays (-1d );
Response. cookies. add (mycookie );
}
Prevent cookie Spoofing
According to browser conventions, only cookies from the same domain name can be read and written, while cookies are only for browsers and have no impact on communication protocols. Therefore, cookie spoofing can be performed in many ways, the easiest way is to build a website by yourself. In c: windowssystem32driversetchosts, set the website you have set up as the domain name you want to cheat. After the cookie is written, the hosts value will be changed back, in this way, the cookie of the local website can be thrown to the domain name you want to intrude.
Public void logined (modeluser model)
{
Int outtime = getloginouttime ();
Httpcontext. current. response. cookies ["username"]. value = model. user_name;
Httpcontext. current. response. cookies ["username_check"]. value = dessecurity. desencrypt (model. user_name );
Httpcontext. current. response. cookies ["username"]. expires = datetime. now. addminutes (outtime );
Httpcontext. current. response. cookies ["username_check"]. expires = datetime. now. addminutes (outtime );
Setusermodel (model );
}
We can see that two cookie values are saved, all of which are user names. One is encrypted and the other is unencrypted.
The code used to verify logon is as follows:
Public bool islogin ()
{
Bool islogin = false;
If (httpcontext. current. request. cookies ["username"]! = Null)
{
If (httpcontext. current. request. cookies ["username_check"]! = Null)
{
String username = httpcontext. current. request. cookies ["username"]. value;
String usernamecheck = httpcontext. current. request. cookies ["username_check"]. value;
If (username = dessecurity. desdecrypt (usernamecheck ))
Islogin = true;
}
}
Return islogin;
}