[Authorize]
public ActionResult Index()
標(biāo)記的方式,可以實現(xiàn)所標(biāo)記的ACTION必須是認(rèn)證用戶才能訪問;
通過使用
[Authorize(Users="username")]
的方式,可以實現(xiàn)所標(biāo)記的ACTION必須是某個具體的用戶才能訪問,以上兩種方式使用起來非常方便,在NeedDinner示例程序中已有具休的實現(xiàn)過程,
但是,我們在實際的應(yīng)用中所使用的大都是基于角色(Roles)的認(rèn)證方式,NeedDinner中卻未給出,本文給出具體實現(xiàn)(基于ASP.NET Forms驗證)過程:
step 1
在完成UserName和Password認(rèn)證后,向客戶端寫入認(rèn)證Cookie
代碼
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(20),
false,
"admin"//寫入用戶角色
);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
step 2
在Global.asax.cs文件中加入以下代碼,用于在用戶登陸網(wǎng)站時讀取Cookie
代碼
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == "")
{
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch
{
return;
}
string[] roles = authTicket.UserData.Split(new char[] { ';' });
if (Context.User != null)
{
Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
}
}
step 3
這樣以來,就可以使用實現(xiàn)以下效果
[Authorize(Roles="admin")]
public ActionResult Index(int ? page)