MVC 基於FormsAuthentication 方式的權限驗證


1.登錄的代碼

 1 [HttpPost]
 2         public ActionResult Index(User entity)
 3         {
 4             User user = GetUser(entity.Name, entity.Password);
 5             if (user != null)
 6             {
 7                 FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
 8                             1,
 9                             user.UserID.ToString(),
10                             DateTime.Now,
11                             DateTime.Now.AddMinutes(30),
12                             false,
13                             user.RoleNames.XJoin(","));
14                 string encTicket = FormsAuthentication.Encrypt(authTicket);
15                 HttpCookie cookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
16                 if (cookie == null)
17                 {
18                     cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
19                 }
20                 cookie.Value = encTicket;
21                 HttpContext.Response.AppendCookie(cookie);
22                 return RedirectToAction("Index", "Test");
23             }
24             return View();
25         }
FormsAuthenticationTicket的user.RoleNames.XJoin(",")是我自己寫的擴展方法,表示用","分隔開的字符串。
生成票據

2.Global.asax中的代碼

 1 protected void Application_AuthenticateRequest(Object sender, EventArgs e)
 2         {
 3             if (HttpContext.Current.User != null)
 4             {
 5                 if (HttpContext.Current.User.Identity.IsAuthenticated)
 6                 {
 7                     if (HttpContext.Current.User.Identity is FormsIdentity)
 8                     {
 9                         FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
10                         FormsAuthenticationTicket ticket = id.Ticket;
11                         string userData = ticket.UserData;
12 
13                         string[] roles = userData.Split(',');
14                         HttpContext.Current.User = new GenericPrincipal(id, roles);
15                     }
16                 }
17             }
18         }
給用戶票據的時候在里面加了一個字符串的角色信息,比如“Administrator”,當一個請求過來的時候asp.net會有一個Application_AuthenticateRequest的事件,專門用於用戶認證授權,在這個事件中我們只需要將這個字符表達的角色重建給用戶就可以,我們在Global.asax的Application_AuthenticateRequest方法中增加如下代碼

3.Controller中的代碼

 1     [Authorize(Roles="sysadmin")]
 2     public class TestController : Controller
 3     {
 4         public ActionResult Index()
 5         {
 6             return View();
 7         }
 8     }

Roles參數可以包含多個Role,比如([Authorize(Roles="sysadmin,conadmin")]),Authorize屬性頁可以具體控制到某個action,只需要將其寫到對應Action方法的屬性上即可。

4.webConfig中的代碼

1 <authentication mode="Forms">
2       <forms loginUrl="~/Login/Index" timeout="2880" />
3 </authentication>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM