webAPI中使用FormsAuthenticationTicket作为登录权限票据
最近在做的项目得到经验,在做登录的时候,使用FormsAuthenticationTicket,
登录成功以后生成cookia作为登录态维护,票据作为调用其他接口的凭据,票据生成后传到前台作为调用接口的凭证,这里有二种情况
一:不在登录的时候使用cookia,而是根据用户名和webconfig里面的设置使用cookia作为登录的时效维护
(1)登录成功以后
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
account,
DateTime.Now,
DateTime.Now.AddHours(12),
true,
JsonConvert.SerializeObject(userData),
FormsAuthentication.FormsCookiePath);
string ticString = FormsAuthentication.Encrypt(ticket);
FormsAuthentication.SetAuthCookie(account, true); //当没有设置cookies身份验证的时候,按照webconfig的设置表单验证,可设置cookia过期时间的滑动
(2)webconfig里面设置
<system.web>
<authentication mode="Forms">
<!--cookia自动滑动十分钟-->
<forms name=".ASPXAUTH" loginUrl="~/Users/Login" defaultUrl="~/Home/Index" protection="All" timeout="1" path="/" requireSSL="false" slidingExpiration="true" enableCrossAppRedirects="false" cookieless="UseDeviceProfile" domain="" />
</authentication>
<system.web>
name可以自定义,缺省时ASPXAUTH
二: 官方说:FormsAuthenticationTicket的IsPersistent 属性字段标志 是否为持久化cookie 会话性cookie保存于内存中。关闭浏览器则会话性cookie会过期消失;持久化cookie则不会,直至过期时间已到或确认注销。
但是我试验的结果是,均不能持久化,均会在设置的过期时间到来的时候便凭据失效
(1)登录成功以后,根据用户生成票据,并设置cookia的过期时间,cookia和tict凭据在到期时间都会清空或者失效
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
account,
DateTime.Now,
DateTime.Now.AddHours(12),
true,
JsonConvert.SerializeObject(userData),
FormsAuthentication.FormsCookiePath);
string ticString = FormsAuthentication.Encrypt(ticket);
var tict = new HttpCookie(FormsAuthentication.FormsCookieName, ticString);
tict.HttpOnly = true;
if (ticket.IsPersistent) //是否为持久化cookie 会话性cookie保存于内存中。关闭浏览器则会话性cookie会过期消失;持久化cookie则不会,直至过期时间已到或确认注销。
{
tict.Expires = ticket.Expiration; //设置cookie到期时间
}
//把票据信息写入Cookie和Session
//SetAuthCookie方法用于标识用户的Identity状态为true
HttpContext.Current.Response.Cookies.Add(tict); // 若不设置cookia的过期时间,默认关闭浏览器(会话)清空cookia,若有设置则按照设置的过期时间
(2)登录成功以后,根据用户生成票据,不设置cookia的过期时间,cookia会在关闭浏览器(会话)清空cookia清空和tict凭据在到期时间或者失效
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
account,
DateTime.Now,
DateTime.Now.AddHours(12),
true,
JsonConvert.SerializeObject(userData),
FormsAuthentication.FormsCookiePath);
string ticString = FormsAuthentication.Encrypt(ticket);
var tict = new HttpCookie(FormsAuthentication.FormsCookieName, ticString);
//把票据信息写入Cookie和Session
//SetAuthCookie方法用于标识用户的Identity状态为true
HttpContext.Current.Response.Cookies.Add(tict); // 若不设置cookia的过期时间,默认关闭浏览器(会话)清空cookia,若有设置则按照设置的过期时间
在接口过滤器里面,首先判断登录是否过期,没过期的话则获取前台调用接口时的header,进行解密,获取用户的数据和权限等账号信息,别人系统有三种用户类型,也放到这个过滤器里面判断处理并根据接口的需求修改接口的参数
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
var userCookia = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (userCookia != null)
{
var auther = actionContext.Request.Headers.Authorization;
if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
{
return;
}
if (auther == null)
{
//actionContext.Response.ReasonPhrase = "登录已过期,请重新登录";
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
new {messages = "登录票据已过期,请重新登录获取", resultCode = 1});
//HttpContext.Current.Response.Redirect("~/Views/Home/Index.cshtml"); //跳到登陆页面
}
else
{
if (auther.Scheme == "Basic" && !string.IsNullOrEmpty(auther.Parameter))
{
var userData = Functions.JudgeSession(auther.Parameter.Trim());
if (userData == null)
{
//actionContext.Response.ReasonPhrase = "登录已过期,请重新登录";
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
new { messages = "登录票据已过期,请重新登录获取", resultCode = 1 });
// HttpContext.Current.Response.Redirect("~/Views/Home/Index.cshtml"); //跳到登陆页面
}
else
{
actionContext.ActionArguments["account"] = userData.GetValue("account").ToString();
if (!actionContext.ActionArguments.ContainsKey("accountType")) return;
actionContext.ActionArguments["accountType"] = userData.GetValue("accountType").ToString();
if (
!JudgeLoginAccount(userData.GetValue("accountType").ToString(), actionContext,
userData.GetValue("account").ToString()))
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest,
new {messages = "当前登录账号不存在", resultCode = 1});
}
}
}
else
{
//actionContext.Response.ReasonPhrase = "登录已过期,请重新登录";
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
new { messages = "登录票据已过期,请重新登录获取", resultCode = 1 });
// HttpContext.Current.Response.Redirect("~/Views/Home/Index.cshtml"); //跳到登陆页面
}
}
}
else
{
//actionContext.Response.ReasonPhrase = "登录已过期,请重新登录";
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
new { messages = "登录已过期,请重新登录", resultCode = 1 });
// HttpContext.Current.Response.Redirect("~/Views/Home/Index.cshtml"); //跳到登陆页面
}
}
public bool JudgeLoginAccount(string type, HttpActionContext actionContext, string account)
{
var Type = Convert.ToInt32(type);
var requestUrlString = actionContext.Request.RequestUri + "当前登录用户不存在用户不存在";
if (Type == 0) //维保总账号
{
if (_staffService.LoadEntity(o => o.Account == account && o.ParentID == 0).SingleOrDefault() ==
null)
{
var str = "登录的维保总账号不存在";
YYTLog.Record(requestUrlString, str); //写入日志
return false;
}
}
else if (Type == 1) //维保子账号
{
if (_staffService.LoadEntity(o => o.Account == account && o.ParentID != 0).SingleOrDefault() ==
null)
{
var str = "登录的监管人员账号不存在";
YYTLog.Record(requestUrlString, str); //写入日志
return false;
}
}
else if (Type == 2) //监管人员
{
if (_supervisorService.LoadEntity(o => o.Account == account).SingleOrDefault() == null)
{
var str = "登录的监管人员账号不存在";
YYTLog.Record(requestUrlString, str); //写入日志
return false;
}
}
else
{
var str = "登录的监管人员账号类型有误";
YYTLog.Record(requestUrlString, str); //写入日志
return false;
}
return true;
}