是的,您可以使用表单身份验证进行一些自定义自动化,但您需要进行一些自定义。
首先,您必须自定义AuthenticateRequest
应用程序的事件以使用角色,因此,Global.asax
您必须设置代码以将其自定义为当前用户:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
if (HttpContext.Current.User.Identity.IsAuthenticated)
if (HttpContext.Current.User.Identity is FormsIdentity)
{
var id = (FormsIdentity)HttpContext.Current.User.Identity;
var ticket = id.Ticket;
// Get the stored user-data, in this case, our roles
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
当您对用户进行身份验证时,您必须设置角色,因此在您的控制器上,您必须使用如下代码对身份验证进行发布操作:
if (LoginService.Validate(userame, password)
{
FormsAuthentication.Initialize();
var ticket = new FormsAuthenticationTicket(1,
username, //user
DateTime.Now, //begin
DateTime.Now.AddHours(3), //timeout
false, //remember?
permission, // permission.. "admin" or for more than one "admin,marketing,sales"
FormsAuthentication.FormsCookiePath);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
HttpContext.Current.Response.Cookies.Add(cookie);
}
之后,您将能够使用类似于您的帖子的代码:
if (User.IsInRole("Admin"))
{ /** do something / }
或者
if (User.IsInRole("Admin") || (User.IsInRole("Marketing") && User.IsInRole("Sales")))
{ /** do something / }
也可以查看Authorize
asp.net mvc属性上的角色:
[Authorize(Roles = "Admin")]
public class CompanyController : Controller
{
// actions
}
编辑
您可以有一个表来将权限“管理员”与某些特权(编辑评论、删除评论等......可以存储在数据库的表中)相关联。尝试这样的事情来实现自定义检查权限:
public static class UserExtension
{
private static bool RoleHasPrivilege(string role, int privilege)
{
// performe a database/cache access to check if the role has the privilege
}
public static bool IsInRole(this IPrincipal user, string role, int privilege)
{
// check if the user authenticate has the "role" permission and the privilege is associate with this role...
return user.IsInRole(role) && RoleHasPrivilege(role, privilege);
}
}
你可以使用:
if (User.IsInRole("Admin", 1))
{
// "Admins" has access
// 1 - can edit posts... for sample
}