新聞中心
一、如何禁止匿名訪問
成都創(chuàng)新互聯成立與2013年,先為扎囊等服務建站,扎囊等地企業(yè),進行企業(yè)商務咨詢服務。為扎囊企業(yè)網站制作PC+手機+微官網三網同步一站式服務解決您的所有建站問題。
1,配置Web.config文件
2,控制器代碼
①:阻止匿名訪問:
[Authorize]
public ActionResult Edit(int id)
{
PersonError person = db.PersonErrors.Single(r => r.STU_ID == id);
return View(person);
}
②:還可以阻止匿名訪問整個控制器:
[Authorize]
public class PersonErrorController : Controller
{
}
③:創(chuàng)建一個身份驗證票證(有了這個就可以訪問頁面了)
returnUrl:返回的路徑
[HttpPost]
public ActionResult ZhangDi(string txtname, string returnUrl)
{
//第二個參數為true會記住密碼
FormsAuthentication.SetAuthCookie(txtname, false);
//判斷是否是有效的路徑
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("http://") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
④:獲取用戶名稱
//是否驗證了用戶
if(User.Identity.IsAuthenticated)
{
//獲取用戶名稱
string username = User.Identity.Name;
}
⑤:刪除身份驗證票證
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
二、對特定角色訪問權限控制
1,配置Web.config文件
2,多種授權方式
①:對多個角色授權訪問:
[Authorize(Roles="admin,superadmin")]
public class PersonErrorController : Controller
{
}
②:對多個用戶授權訪問:
[Authorize(Users="test1,test2")]
public class PersonErrorController : Controller
{
}
③:同時授權給用戶和角色
[Authorize(Roles="admin,user",Users="test1,test2")]
public class PersonErrorController : Controller
{
}
3,控制器代碼
①:在Global.asax配置Application_AuthenticateRequest事件(當安全模塊已建立用戶標識時發(fā)生)
protected void Application_AuthenticateRequest() { if (HttpContext.Current.User != null) { if (HttpContext.Current.User.Identity.IsAuthenticated) { if (HttpContext.Current.User.Identity is FormsIdentity) { FormsIdentity userident = (FormsIdentity)HttpContext.Current.User.Identity; string UserData = userident.Ticket.UserData; string[] roles = UserData.Split(','); //設置用戶角色 HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(userident, roles); } } } }
②:創(chuàng)建一個身份驗證票證
[HttpPost] public ActionResult ZhangDi(string txtname, string returnUrl) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1,//票證的版本號 txtname,//用戶名 DateTime.Now,//票證發(fā)出的時間 DateTime.Now.AddHours(1),//票證過期時間 false , //是否將票證持久存儲在cookie中(和記住密碼沒關系) "admin");//角色 //加密驗證票證 string ticketEncrypt = FormsAuthentication.Encrypt(ticket); //實例化cookie HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketEncrypt); //記住密碼 cookie.Expires = DateTime.MaxValue; cookie.Path = "/"; //將cookie添加到cookie集中 Response.Cookies.Add(cookie); return Redirect(returnUrl); }
③:獲取用戶名稱
//是否驗證了用戶
if(User.Identity.IsAuthenticated)
{
//獲取用戶名稱
string username = User.Identity.Name;
}
④:刪除身份驗證票證
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
本文題目:MVC3----應用程序的安全性(1)之Authorize
網站網址:http://www.ef60e0e.cn/article/iijhjg.html