一、如何禁止匿名访问

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
{
}
③:创建一个身份验证票证(有了这个就可以访问页面了)
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("//") && !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事件(当安全模块已建立用户标识时发生)
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);
}
}
}
}②:创建一个身份验证票证
[HttpPost]
public ActionResult ZhangDi(string txtname, string returnUrl)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,//票证的版本号
txtname,//用户名
DateTime.Now,//票证发出的时间
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");
}
创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。
分享题目:MVC3----应用程序的安全性(1)之Authorize-创新互联
网页链接:http://www.jxjierui.cn/article/dedeej.html


咨询
建站咨询
