一般情况下,在我们做访问权限管理的时候,会把用户的正确登录后的基本信息保存在Session中,以后用户每次请求页面或接口数据的时候,拿到

Session中存储的用户基本信息,查看比较他有没有登录和能否访问当前页面。

       Session的原理,也就是在服务器端生成一个SessionID对应了存储的用户数据,而SessionID存储在Cookie中,客户端以后每次请求都会带上这个

Cookie,服务器端根据Cookie中的SessionID找到存储在服务器端的对应当前用户的数据。

       FormsAuthentication是微软提供给我们开发人员使用,做身份认证使用的。通过该认证,我们可以把用户Name 和部分用户数据存储在Cookie中,

通过基本的条件设置可以,很简单的实现基本的身份角色认证。

       这里要实现的效果是:在不使用membership的情况下,使用系统提供的Authorize 实现基于角色的访问控制。

1、创建认证信息 Ticket 

  在用户登录以后,把用户的ID和对应的角色(多个角色用,分隔),存储在Ticket中。

  使用FormsAuthentication.Encrypt 加密票据。

  把加密后的Ticket 存储在Response Cookie中(客户端js不需要读取到这个Cookie,所以最好设置HttpOnly=True,防止浏览器攻击窃取、伪造Cookie)。这样下次可以从Request Cookie中读取了。

  一个简单的Demo如下:

 1 public ActionResult Login(string uname) 
 2         {
 3             if (!string.IsNullOrEmpty(uname)) 
 4             {
 5                 //FormsAuthentication.SetAuthCookie(uname,true);
 6                 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
 7                     (   1,
 8                         uname,
 9                         DateTime.Now,
10                         DateTime.Now.AddMinutes(20),
11                         true,
12                         "7,1,8",
13                         "/"
14                     );
15                 var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,FormsAuthentication.Encrypt(ticket));
16                 cookie.HttpOnly = true;
17                 HttpContext.Response.Cookies.Add(cookie);
18 
19                 return RedirectToAction("UserPage");
20             }
21             return RedirectToAction("Index");
22         }
View Code

相关文章: