点对点登录实现原理及源码,一个用户只能在一处登陆(简单)
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://zgcwkj.com/archives/32.html
转载声明:请注明本文章的标题及内容的出处和声明,谢谢
牛逼