马上要用做安卓APP了,前后端分离的,后台必然要写WebAPI 来做操作,
但是API不可能给任何人使用,所以要加身份验证来过滤非法请求,话不多说一起来看吧。
1.创建项目
2.创建AP控制器
3.废话半天开始编码(简单登陆分配Token令牌)
前台代码
@using (Html.BeginForm("Index", "Default", FormMethod.Post))
{
<div>
<input type="text" name="username" />
<input type="text" name="pwd" />
<input type="submit" value="登陆">
</div>
}
控制器代码
[HttpPost]
public ActionResult Index(string username, string pwd)
{
if (IsTrue(username, pwd))
{
//生成令牌
//重点在这里
//命名空间 System.Web.Security 参数分别问版本,Cookie名称 ,当前时间,结束时间,是否持续为持续性Cookie(True,False),数据,Cookie存放路径
System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(0, username, DateTime.Now,
DateTime.Now.AddHours(1), true, string.Format("{0}&{1}",
username, pwd), System.Web.Security.FormsAuthentication.FormsCookiePath);
//加密
string ticketNum = System.Web.Security.FormsAuthentication.Encrypt(ticket);
if (ticketNum != null && ticketNum.Trim().Length > 0)
{
return RedirectToAction("Show", "Default", new { ticket = ticketNum });
}
}
else
{
}
return View();
}
public ActionResult Show(string ticket)
{
ViewBag.pp = ticket;
return View();
}
public bool IsTrue(string name, string pwd)
{
if (name == "123" && pwd == "123")
{
return true;
}
else
{
return false;
}
}
Show视图的显示
<body>
Token:
@ViewBag.pp
</body>
就这么简单Token加密的生成成功了 明天写实际用法~不积跬步无以至千里,不计小流无以成江海~