一、如何禁止匿名访问


1,配置Web.config文件

<authenticationmode="Forms"><formsloginUrl="~/Account/ZhangDi"timeout="2880"/></authentication>

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文件

<authenticationmode="Forms"><formsloginUrl="~/Account/ZhangDi"timeout="2880"/></authentication>

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事件(当安全模块已建立用户标识时发生)

protectedvoidApplication_AuthenticateRequest(){if(HttpContext.Current.User!=null){if(HttpContext.Current.User.Identity.IsAuthenticated){if(HttpContext.Current.User.IdentityisFormsIdentity){FormsIdentityuserident=(FormsIdentity)HttpContext.Current.User.Identity;stringUserData=userident.Ticket.UserData;string[]roles=UserData.Split(',');//设置用户角色HttpContext.Current.User=newSystem.Security.Principal.GenericPrincipal(userident,roles);}}}}

②:创建一个身份验证票证

[HttpPost]publicActionResultZhangDi(stringtxtname,stringreturnUrl){FormsAuthenticationTicketticket=newFormsAuthenticationTicket(1,//票证的版本号txtname,//用户名DateTime.Now,//票证发出的时间DateTime.Now.AddHours(1),//票证过期时间false,//是否将票证持久存储在cookie中(和记住密码没关系)"admin");//角色//加密验证票证stringticketEncrypt=FormsAuthentication.Encrypt(ticket);//实例化cookieHttpCookiecookie=newHttpCookie(FormsAuthentication.FormsCookieName,ticketEncrypt);//记住密码cookie.Expires=DateTime.MaxValue;cookie.Path="/";//将cookie添加到cookie集中Response.Cookies.Add(cookie);returnRedirect(returnUrl);}

③:获取用户名称

//是否验证了用户
if(User.Identity.IsAuthenticated)
{
//获取用户名称
string username = User.Identity.Name;
}

④:删除身份验证票证

public ActionResult LogOff()
{
FormsAuthentication.SignOut();

return RedirectToAction("Index", "Home");
}