网站开发不可避免的要开发一些验证模块,很多模块经常有“记住用户名和密码”的相关选项。
在.net中,可以使用系统框架中的类来进行验证中用户名和密码的COOKIE存值。
当然这个过程是经过了加密的,以下的代码就是一个简单的示例。
一、首先创建一个myCookie.cs文件:
namespace Cookies
{
public class MyCookies
{
public static HttpCookie SendCookie(string name, string pwd)
{
//创建一个票证实例
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "ansen", DateTime.Now, DateTime.Now.AddDays(1), true, "UserRole", "/");
//创建加密的COOKIE身份验证票证
string hashTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
cookie.Values["name"] = name;
string md5pass = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "MD5");
cookie.Values["password"] = md5pass;
cookie.Expires = DateTime.Now.AddDays(1);
return cookie;
}
}
}
二、主页面中,进行调用:
namespace Cookies
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
InitPage();
}
}
protected void InitPage()
{
if (Session["ansen"] != null)
{
Response.Write("用户已经登录!");
}
else if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
string name = Request.Cookies[FormsAuthentication.FormsCookieName]["name"].ToString();
string pwd = Request.Cookies[FormsAuthentication.FormsCookieName]["password"].ToString();
if (pwd == (System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("123456", "MD5")))
{
Session["ansen"] = name;
Response.Write("用户从COOKIE登录!");
txtName.Text = name;
txtPwd.Text = pwd;
}
}
else
{
Response.Write("还未登录!");
}
}
protected void btnSumbit_Click(object sender, EventArgs e)
{
if (txtName.Text == "ansen" && txtPwd.Text == "123456")
{
Session["ansen"] = txtName.Text;
Response.Cookies.Add(MyCookies.SendCookie(txtName.Text, txtPwd.Text));
Response.Write("用户登录成功!");
}
else
{
Response.Write("用户登录失败!");
}
}
protected void btnSignOut_Click(object sender, EventArgs e)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
Response.Cookies.Clear();
FormsAuthentication.SignOut();
}
if (Session["ansen"] != null)
{
Session.Abandon();
}
Response.Redirect("Default.aspx");
}
protected void btnSession_Click(object sender, EventArgs e)
{
if (Session["ansen"] != null)
{
Session.Abandon();
}
}
}
}
其中,默认用户名和密码:ansen/123456