通用权限案例平台--登录认证
通用权限管理系统平台采用Froms认证方式实现对用户登录,为解决session超时问题,导致用户重复登录的问题,系统采用cookies保存,并实现灵活保存登录信息。
实现Forms认证,需要在web.config增加配置项
<authentication mode="Forms">
<forms loginUrl="~/Home/LogOn" timeout="2880" slidingExpiration="true" cookieless="UseCookies"/>
<!--采用滑动时间-->
</authentication>
自定义实现Authentication类,并实现创建登录用户的票据信息方法
/// <summary>
/// 创建登录用户的票据信息
/// </summary>
/// <param name="strUserName"></param>
/// <param name="strPassword"></param>
/// <param name="strIP"></param>
public static void CreateLoginUserTicket(string strUserName, string strPassword,string strIP)
{
//构造Form验证的票据信息
TUserDo mUserEntity=new TUserDo();
Filter filter = Filter.Null;
filter.And(Filter.Eq("LoginId", strUserName.Trim()));
filter.And(Filter.Eq("Password", Common.Md5Encrypt(strPassword.Trim())));
filter.And(Filter.Eq("IsDelete", "0"));
filter.And(Filter.Eq("IsUser", "0"));
List<TUserDo> list = DataAccess.FindByFilter<TUserDo>(filter);
if(list.Count>0)
{
mUserEntity=list[0];
}
int expires = ConvertData.ToInt(System.Configuration.ConfigurationManager.AppSettings["CookiesExpires"].ToString().Trim(), 1);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, mUserEntity.UserGuid, DateTime.Now, DateTime.Now.AddHours(expires),
true, string.Format("{0}",strIP), FormsAuthentication.FormsCookiePath);
string ticString = FormsAuthentication.Encrypt(ticket);
//把票据信息写入Cookie和Session
//SetAuthCookie方法用于标识用户的Identity状态为true
#region Cookies
HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, ticString));
HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName].Expires = System.DateTime.Now.AddHours(expires);
FormsAuthentication.SetAuthCookie(mUserEntity.UserGuid, true);
#endregion Cookies
//HttpContext.Current.Session[EAPConst.eap_ipAdress] = strIP;
//HttpContext.Current.Items[EAPConst.eap_ipAdress] = strIP;
//重写HttpContext中的用户身份,可以封装自定义角色数据;
HttpContext.Current.Response.Cookies.Add(new HttpCookie(EAPConst.eap_Adress, ticket.UserData));
HttpContext.Current.Response.Cookies[EAPConst.eap_Adress].Expires = System.DateTime.Now.AddHours(expires);
string[] info = ticket.UserData.Split(',');
IIdentity identity = new FormsIdentity(ticket);
IPrincipal principal = new GenericPrincipal(identity, info);
HttpContext.Current.User = principal;
}
/// <summary>
/// 用户注销执行的操作
/// </summary>
public static void Logout()
{
System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Values.Clear();
FormsAuthentication.SignOut();
}
}
登录认证直接调用该方法进行认证。