.net实现网站用户登录认证
cookie登录后同域名下的网站保持相同的登录状态。
登录
private void SetAuthCookie(string userId, bool createPersistentCookie)
{ var ticket = new FormsAuthenticationTicket(2, userId, DateTime.Now, DateTime.Now.AddDays(7), true, "", FormsAuthentication.FormsCookiePath)
string ticketEncrypted = FormsAuthentication.Encrypt(ticket)
HttpCookie cookie
if (createPersistentCookie)//是否在设置的过期时间内一直有效
{ cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketEncrypted)
{ HttpOnly = true, Path = FormsAuthentication.FormsCookiePath, Secure = FormsAuthentication.RequireSSL, Expires = ticket.Expiration, Domain = "cnblogs.com"//这里设置认证的域名,同域名下包括子域名如aa.cnblogs.com或bb.cnblogs.com都保持相同的登录状态 }
} else
{ cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketEncrypted)
{ HttpOnly = true, Path = FormsAuthentication.FormsCookiePath, Secure = FormsAuthentication.RequireSSL, //Expires = ticket.Expiration,//无过期时间的,浏览器关闭后失效 Domain = "cnblogs.com" }
} HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName)
HttpContext.Current.Response.Cookies.Add(cookie)
}
这样登录后,在同域名下的任何页面都可以得到用户状态
判断用户是否登录
public bool IsAuthenticated
{ get
{ bool isPass = System.Web.HttpContext.Current.User.Identity.IsAuthenticated
if (!isPass) SignOut()
return isPass
}}
得到当前的用户名
public string GetCurrentUserId()
{ return _httpContext.User.Identity.Name
}
下面给大家一个具体的实例
CS页代码:
using System
using System.Data
using System.Configuration
using System.Collections
using System.Web
using System.Web.Security
using System.Web.UI
using System.Web.UI.WebControls
using System.Web.UI.WebControls.WebParts
using System.Web.UI.HtmlControls
using System.Data.SqlClient
public partial class Login : System.Web.UI.Page
{protected void Page_Load(object sender, EventArgs e)
{}protected void Button1_Click(object sender, EventArgs e)
{ string connString = Convert.ToString(ConfigurationManager.ConnectionStrings["001ConnectionString"])
//001ConnectionString是我在webconfig里配置的数据库连接。SqlConnection conn = new SqlConnection(connString)
string strsql = "select * from User_table where User_name=&apos
" + UserName.Text + "&apos
and Password=&apos
" + Password.Text + "&apos
"
SqlCommand cmd = new SqlCommand(strsql, conn)
conn.Open()
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
if (dr.Read())
{ Response.Redirect("index.aspx")
conn.Close()
}else
{FailureText.Text = "登陆失败,请检查登陆信息!"
conn.Close()
Response.Write("")
}}protected void Button2_Click(object sender, EventArgs e) //文本框重置按钮
{UserName.Text = ""
Password.Text = ""
}}
下面是aspx页面代码:
<
%@ Page Language="C
#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>无标题页
.net实现网站用户登录认证