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);
}
}
这是插入cookie的代码
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);
}
}
最后是删除cookie的方法
protected void button2_click(object sender, eventargs e)
{
httpcookie mycookie = new httpcookie("username");
mycookie.expires = datetime.now.adddays(-1d);
response.cookies.add(mycookie);
}
防止cookie 欺骗
按照浏览器的约定,只有来自同一域名的cookie才可以读写,而cookie只是浏览器的,对通讯协议无影响,所以要进行cookie欺骗可以有多种途径,最简单的方法自己建立一个网站,在c:windowssystem32driversetchosts 中把这个自己建立的网站制定成想要欺骗的域名,cookie写入以后再把hosts的值改回来,这样这个本地的网站的cookie就可以抛到你想要入侵的域名下
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);
}
可以看到保存了两个cookie值,都是用户名,一个是加密的一个是未加密的
验证是否登陆的代码如下:
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;
}