1. asp.net 1.1登录代码:
private const string myDomain = ".mywebsite.com";
static HttpCookie GetAuthCookie(string key, string value)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
key,
System.DateTime.Now,
DateTime.Now.AddMinutes(20),
false,
value,
FormsAuthentication.FormsCookiePath);
string encTicket = FormsAuthentication.Encrypt(ticket);
if ((encTicket == null) || (encTicket.Length < 1))
{
throw new HttpException("Unable_to_encrypt_cookie_ticket");
}
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
cookie.Path = FormsAuthentication.FormsCookiePath;
cookie.Domain= myDomain ;
cookie.Secure = FormsAuthentication.RequireSSL;
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
return cookie;
}
static void SignIn(string userName,string password)
{
if(userName == "***" && password == "***")
{
string key = "***";
string value = "***";
HttpContext.Current.Response.Cookies.Add(GetAuthCookie(key,value));
}
}
2. asp.net 1.1登出代码:
static void SignOut()
{
FormsAuthentication.SignOut();
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, string.Empty);
cookie.Expires = DateTime.Now.AddMinutes(-1);
cookie.Path = FormsAuthentication.FormsCookiePath;
cookie.Domain= myDomain ;
HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
HttpContext.Current.Response.Cookies.Set(cookie);
}
3. asp.net 1.1验证登陆状态代码:
static bool CheckSignStatus()
{
HttpContext csContext = HttpContext.Current;
if (csContext.User != null && csContext.User.Identity.IsAuthenticated && csContext.User.Identity.Name != string.Empty)
{
return true;
}
return false;
}
4. asp.net 1.1 web.config配置如下:
<system.web>
<authentication mode="Forms" />
<machineKey validationKey="AutoGenerate" decryptionKey="AutoGenerate" validation="SHA1"/>
</system.web>
5. 说明:
在登出时,使用删除Cookie的方法,是因为在asp.net 1.1中,FormsAuthentication没有Domain属性,如果设置了Cookie的Domain,直接用FormsAuthentication.SignOut()无法登出。
如果站点部署在多台服务器上,web.config文件中machineKey 节点必须保持一致