一、ASP.NET票據驗證
1、在根目錄建立一個Global.asax文件,烤入一段代碼
protected void Application_AuthenticateRequest(object SENDER, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket tiecket = id.Ticket;
string userData = tiecket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
}
}
}
}
2、在web.config 文件中配置目錄權限及登錄頁,登錄頁,在system.web節點中
//mode="Forms"指采用表單驗證,
//name指名稱,
//loginUrl轉到的url,
//protection所有頁面 //path路徑/根目錄
<authentication mode="Forms">
<forms name="mycook" loginUrl="login_direct.aspx" protection="All" path="/" />
</authentication>
loginUrl="login_direct.aspx"代碼如下: 直接寫在page_load中
string strReturnURL = Request.Params["ReturnUrl"];
if (strReturnURL.Contains("admin"))
{
Response.Redirect("admin/login.aspx?ReturnURL=default.aspx");
}
else if (strReturnURL != null && strReturnURL.Contains("admin"))
{
Response.Redirect("admin/login.aspx?ReturnURL=" + strReturnURL);
}
else
{
Response.Redirect("index.aspx?ReturnURL=" + strReturnURL);
}
3、配置目錄權限,在system.web節點外面
//path路徑,authorization授權,allow允許,roles角色,deny拒絕
第一段代碼 admin目錄只授權于admin角色拒絕所有的用戶
第二段代碼 user目錄只授權于user角色拒絕所有的用戶
第三段代碼 admin/login.aspx文件允許所有用戶打開如該文件有圖片及樣式應再加上images和css或js文件夾也允許所有用戶打開
<location path="admin">
<system.web>
<authorization>
<allow roles="admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<location path="admin/login.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="admin/css">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="admin/images">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="user">//路徑
<system.web>
<authorization>
<allow roles="user"/>//角色
<deny users="*"/>
</authorization>
</system.web>
</location>
4、在登錄頁的登錄事件中的登錄成功后烤入一段代碼,如登錄到user中心則采用user角色
HttpCookie cook;
string strReturnURL; //登錄成功后返回的URL
string roles = "user"; //用戶角色
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, name, DateTime.Now, DateTime.Now.AddMinutes(30), false, roles);
cook = new HttpCookie("mycook");
cook.Value = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(cook);
strReturnURL = Request.Params["ReturnUrl"];
if (strReturnURL != null && strReturnURL.Contains(".aspx"))
{
Response.Redirect(strReturnURL);
}
else
{
Response.Redirect("user/index.aspx");
}
//獲取登錄的用戶名
litusername.Text = User.Identity.Name;
<%=User.Identity.Name %>
//通過登錄的用戶名獲取Model
Model.User model = udao.GetModel(User.Identity.Name);
//退出
FormsAuthentication.SignOut();
//判斷是否登錄
if (!User.Identity.IsAuthenticated)
{
Utility.Tool.Alert("請先登錄", this.Page);
return;
}
5、登錄
LoginView 登錄控件 注:以下都是放在LoginView控件中
AnonymousTemplate節點登錄時的樣式
LoggedInTemplate節點登錄后的樣式
LoginName登錄后顯示的用戶名控件
LoginStatus登錄后退出的控件
用一個LoginView控件包括起來< AnonymousTemplate>登錄時狀態< LoggedInTemplate>登錄后狀態
找到LoginView控件中的TextBox
txtname.Text=(LoginView1.FindCoutrol("txtname")as TextBox).Text.Trim();
二、用戶自定義驗證
子目錄或虛似目錄的訪問 如http://www.cxlook.com/bbs/default.aspx 或http://bbs.cxlook.com/default.aspx
1、在web.config中的system.web節點上面(外)加上:
<appSettings>
<add key="bbsroot" value="/bbs/" />
</appSettings>
2、指定到bbsroot
string root = System.Configuration.ConfigurationManager.AppSettings["bbsroot"];
3、項目中的Web層右鍵屬性虛似路徑 /bbs/
4、登錄事件
Model.User model = new DAL.UserDAL().LoginByUserName(name, pwd);
if (model == null)
{
model = new DAL.UserDAL().LoginByEmail(name, pwd);
}
if (model == null)
{
Utility.Tool.Alert("用戶名或密碼錯誤", this.Page);
return;
}
Session["user"] = model;
5、創建ValidatorPage.cs類文件 所有user文件夾下所有文件都要繼承該類即 System.Web.UI.Page 改為 ValidatorPage
public class ValidatorPage : System.Web.UI.Page
{
//pageunload事件,并不是指瀏覽器關閉,而是指頁面關閉,所以刷新的時候,依然會執行以下事件
protected void Page_Unload(object sender, EventArgs e)
{
}
//虛似目錄名稱
string root = System.Configuration.ConfigurationManager.AppSettings["bbsroot"];
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if (Session["user"] == null)
{
//這里寫跳轉到登陸頁面例如:
Response.Redirect(string.Format(root + "/login.aspx?page={0}", Request.Path));
}
}
}
5.1后臺管理文件夾admin在所有頁面中加上
string root = System.Configuration.ConfigurationManager.AppSettings["bbsroot"];
if (Session["admin"] == null)
{
Response.Redirect(string.Format(root + "admin/login.aspx?page={0}", Request.Url));
}
6、在所有登錄到user的登錄事件中的Session["user"] = model;后面加上自動轉向
string page = Request.QueryString["page"];
if (string.IsNullOrEmpty(page))
{
Response.Redirect(root + "user/");
}
else
{
Response.Redirect(page);
}
關閉窗口時退出登錄并計算時間
1、在Globl.asax中的Session_End節點中加上7方法
2、在web.config中的<system.web>節點中加上
<sessionState mode="InProc" timeout="20"/>
7、計算用戶在線時間 在Global全局處理程序中的Session_End節點中加上
if (Session["user"] != null)
{
#region 記錄在線時間
Model.User u = Session["user"] as Model.User;
DateTime now = DateTime.Now;
new DAL.LogDAL().Add(new Model.Log()
{
username = u.username,
ip = Request.UserHostAddress,
remark = "Session失效",
createdate = now
});
string tmp = new DAL.LogDAL().GetLastLoginDate(u.username);
if (tmp == "")
{
int t = int.Parse(Math.Round((now - u.createdate).TotalMinutes).ToString());
}
else
{
DateTime dl = DateTime.Parse(tmp);
int t = int.Parse(Math.Round((now - dl).TotalMinutes).ToString());
new DAL.UserDAL().UpdateOnLineTime(u.id, t);
}
#endregion
}
在DAL層中LogDAL.cs中加上獲取最后登錄的時間
public string GetLastLoginDate(string username)
{
string sql = "select top 1 createdate from bbs_log where username=@username and remark='登錄' order by createdate desc";
Database db = DatabaseFactory.CreateDatabase();
DbCommand dbCommand = db.GetSqlStringCommand(sql);
db.AddInParameter(dbCommand, "username", DbType.String, username);
object obj = db.ExecuteScalar(dbCommand);
if (obj == null || obj.ToString() == "")
{
return "";
}
return DateTime.Parse(obj.ToString()).ToString("yyyy-MM-dd HH:mm");
}
8、在所有登錄事件Session["user"] = model;之前加上日志代碼
new DAL.LogDAL().Add(new Model.Log()
{
ip = Request.UserHostAddress,
remark = "登錄",
username = name,
});
9、在所有退出登錄事件中Session["user"] = null;之前加上
DateTime now = DateTime.Now;
new DAL.LogDAL().Add(new Model.Log()
{
username = u.username,
ip = Request.UserHostAddress,
remark = "退出",
createdate = now
});
string tmp = new DAL.LogDAL().GetLastLoginDate(u.username);
if (tmp == "")
{
int t = int.Parse(Math.Round((now - u.createdate).TotalMinutes).ToString());
}
else
{
DateTime dl = DateTime.Parse(tmp);
int t = int.Parse(Math.Round((now - dl).TotalMinutes).ToString());
new DAL.UserDAL().UpdateOnLineTime(u.id, t);
}
//在母版頁中的退出并記錄在線時間
//退出登錄
protected void LinkButton1_Click(object sender, EventArgs e)
{
Model.User model = Session["user"] as Model.User;
List<string> list = Application["online"] as List<string>;
if (list.Contains(model.username))
{
list.Remove(model.username);
}
Application.Lock();
Application["online"] = list;
Application.UnLock();
#region 寫日志并計算在線時間
DAL.LogDAL ldal = new Xiaobin.BBS.DAL.LogDAL();
DateTime now = DateTime.Now;
ldal.Add(new Xiaobin.BBS.Model.Log()
{
username = model.username,
remark = "退出",
ip = Request.UserHostAddress,
createdate = now
});
//取最近一次登錄時間
DAL.UserDAL udal = new Xiaobin.BBS.DAL.UserDAL();
string tmp = ldal.GetLastLoginDate(model.username);
if (tmp == "")
{
//用戶之前沒有登錄過,則以注冊時間為登錄時間來計算
int t = int.Parse(Math.Round((now - model.createdate).TotalMinutes).ToString());
udal.UpdateOnlineTime(model.id, t);
}
else
{
DateTime d1 = DateTime.Parse(tmp);
int t = int.Parse(Math.Round((now - d1).TotalMinutes).ToString());
udal.UpdateOnlineTime(model.id, t);
}
#endregion
Session["user"] = null;
Response.Redirect(root + "login.aspx");
}
在UserDAL.cs中加上更新onlinetime字段方法
public void UpdateOnlineTime(int id, int t)
{
string sql = "update bbs_user set onlinetime=onlinetime+" + t + " where id=" + id;
Database db = DatabaseFactory.CreateDatabase();
db.ExecuteNonQuery(CommandType.Text, sql);
}
10、獲取所有登錄用戶信息 在Global全局處理程序中的Application_Start節點中加上
if (Application["online"] == null)
{
List<string> list = new List<string>();
Application["online"] = list;
}
11、在所有登錄事件寫日志之前加上
List<string> list = Application["online"] as List<string>;
if (!list.Contains(model.username))
{
list.Add(model.username);
}
Application.Lock();
Application["online"] = list;
Application.UnLock();
12、在所有退出事件寫日志之前加上
List<string> list = Application["online"] as List<string>;
if (!list.Contains(u.username))
{
list.Remove(u.username);
}
Application.Lock();
Application["online"] = list;
Application.UnLock();