项目开发-->身份认证及用户登录模块
1.首先明确的两个问题
如何判断当前申请是由一个已登录用户发起的?如果Request.IsAuthenticated为true,则表示是一个已登录用户。
如何获取当前登录用户的登录名?如果是一个已登录用户,访问HttpContext.User.Identity.Name可获取登录名
2.身份认证基础
在ASP.NET中,身份认证可以分为两个阶段:认证和授权
认证阶段:识别当前请求的用户是不是一个可识别(已登录)用户
授权阶段:是否允许当前请求访问指定资源
在认证阶段,ASP.NET会根据web.config设置的认证方式,判断当前请求的用户是否拥有加密后的票据。有,则表示已登录用户;没有,则表示未登录用户(跳转登录页面);
在授权阶段:ASP.NET会根据相应config的设置,判断当前登录用户角色,判断是否拥有访问受限资源的权限
3.实现登录退出
用户登录:首先判断数据库中是否包含改用户信息。false,则返回登录失败;true,则新建票据,对其加密,且写入cookie(身份认证必须数据)
新建票据,对其加密,且写入cookie核心代码如下:
public class HGLMember { /// <summary> /// 会员Id /// </summary> public string Id { get; set; } /// <summary> /// 会员账号 /// </summary> public string Account { get; set; } /// <summary> /// 会员名称 /// </summary> public string Name { get; set; } /// <summary> /// 会员类型 /// </summary> public int Type { get; set; } /// <summary> /// 持久化时间。0,默认;>0 ,单位天;-1,永久持久化 /// </summary> public int Date { get; set; } } public class HGLAuthorize { /// <summary> /// 会员Id /// </summary> public string Id { get; set; } /// <summary> /// 会员账号 /// </summary> public string Account { get; set; } /// <summary> /// 会员名称 /// </summary> public string Name { get; set; } /// <summary> /// 会员类型 /// </summary> public int Type { get; set; } /// <summary> /// 持久化时间。0,默认;>0 ,单位天; /// </summary> public int Date { get; set; } /// <summary> /// 存放cookie /// </summary> public static void SetCookie(HGLMember model) { var expires = DateTime.Now.AddMinutes(30); if (model.Date > 0) expires = DateTime.Now.AddDays(model.Date); //1.创建登录票据,包含登录名以及额外的用户数据。 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, model.Id, DateTime.Now, expires, false, model.ToJsonByJsonNet() ); //2.加密ticket,变成一个加密的字符串。 string cookieValue = FormsAuthentication.Encrypt(ticket); //3.根据加密结果创建登录Cookie System.Web.HttpCookie cookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, cookieValue); cookie.Domain = FormsAuthentication.CookieDomain; cookie.Expires = expires; //4.写登录cookie System.Web.HttpContext.Current.Response.Cookies.Remove(cookie.Name); System.Web.HttpContext.Current.Response.Cookies.Add(cookie); } /// <summary> /// 清除cookie /// </summary> public static void Logoff() { FormsAuthentication.SignOut(); } /// <summary> /// 序列化对象 /// </summary> private static HGLMember Serialize() { FormsIdentity identity = System.Web.HttpContext.Current.User.Identity as FormsIdentity; if (identity == null || identity.Ticket == null || string.IsNullOrEmpty(identity.Ticket.UserData)) return new HGLMember(); return identity.Ticket.UserData.ToObjectByJsonNet<HGLMember>(); } }
用户退出:直接调用代码:FormsAuthentication.SignOut();