點對點登錄實現原理及源碼,一個用戶只能在一處登陸(簡單)
1,以下基於文件實現
需要創建一個文件進行記錄登錄的用戶信息
登錄(驗證)請求,就生成一個隨機碼,返回前台進行保存
每次需要訪問後台時傳遞隨機碼進行匹配,如果一致那麼就代表可以訪問,否則退出
2,以下基於數據庫實現
在用戶表增加一列,用於記錄隨機碼
當用戶登錄(驗證)請求,就通過修改用戶表的隨機碼,把生成的隨機碼保存到數據庫總,並且隨機碼到前台進行保存
每次需要訪問後台時傳遞隨機碼進行匹配,如果一致那麼就代表可以訪問,否則退出
下面是 C#的 MVC 框架 的 文件實現方法
生成模塊
//文件地址
string Tofile = Server.MapPath("~/Content/ftmp/Landing.ini");
//打開文本
string Landing = System.IO.File.ReadAllText(Tofile);
//正則匹配到賬戶登錄過
string History = Regex.Match(Landing, Username + "><" + "..........\r\n").ToString();
//判斷是否存在過
if (History != "")
{
//將存在過的用戶刪除
Landing= Landing.Replace(History, "");
//刪除文本
System.IO.File.Delete(Tofile);
//重新生成文本進行保存
System.IO.File.AppendAllText(Tofile, Landing);
}
//隨機碼
string random = new CheckCode(true, true, false).GoRandom(10);
//生成用戶名對應的隨機碼
System.IO.File.AppendAllText(Tofile, Username + "><" + random + "\r\n");
//--> 設置Cookie
HttpCookie cookie = new HttpCookie("Landing");
cookie["Verification"] = random;
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
return Content("OK");
驗證模塊
//文件地址
string Tofile = Server.MapPath("~/Content/ftmp/Landing.ini");
//打開文本
string Landing = System.IO.File.ReadAllText(Tofile);
//--> 讀取Cookie
HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies["Landing"];
if (cookie != null)
{
if (cookie["Verification"] != null)
{
string Verification = System.Web.HttpContext.Current.Server.UrlDecode(cookie["Verification"]);
if (Landing.Contains(Username + "><" + Verification + "\r\n"))
{
return Content("OK");
}
}
}
return Content("NO");
說明:變量 Username 為用戶名稱
用到的類庫是:生成隨機碼
版權屬於:zgcwkj
本文鏈接:https://www.zgcwkj.com/archives/32.html
轉載聲明:請注明本文章的標題及內容的出處和聲明,謝謝
牛逼