我正在开发一些网站,这是一种在线工作场所,会有一些用户和一些正在进行的计算机编程项目,每个用户可以有多个角色,例如一个特定的用户可以是一个项目的项目经理和另一个项目的开发人员。在项目中,项目经理自然比开发人员拥有更多的权限。我的问题是如何在我的代码中巧妙地管理它?我打算使用我的自定义 Role Provider 并为此使用 Authorize 属性,但这还不够,因为我需要项目 ID 和用户 ID 来查找用户在特定项目中的角色。
最佳答案
首先,您必须为扩展角色管理创建额外的表,例如 projects
以及在 operations
上下文中与 users
的关系,这可能是您的 Controller 的操作
。
一种方法是为角色
创建您自己的表。在那种情况下,您将只使用 Asp net membership users
,但这完全取决于您的要求。
其次你必须在 MVC
中处理它,在我看来最好的方法是通过你自己的自定义 Authorization
属性来实现它,并用你的装饰你的 Controller 的 Action 自定义授权属性而不是 [Authorization]
属性。
非常简单。
[CustomAuthorize]
//[Authorize]
public ActionResult GetProjectTasks(string projectname)
{
}
为此,您必须从 FilterAttribute
继承您的类,并且还必须实现 IAuthorizationFilter
接口(interface)。
public void OnAuthorization(AuthorizationContext filterContext)
{
HttpCookie authCookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var identity = new GenericIdentity(authTicket.Name, "Forms");
var principal = new GenericPrincipal(identity, new string[] { authTicket.UserData });
filterContext.HttpContext.User = principal;
}
var controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
var action = filterContext.ActionDescriptor.ActionName;
var user = filterContext.HttpContext.User;
var ip = filterContext.HttpContext.Request.UserHostAddress;
var isAccessAllowed = CustomAuthenticationLogic.IsAccessAllowed(controller, action, user, ip);
if (!isAccessAllowed)
{
// Code if user is authenticated
FormsAuthentication.RedirectToLoginPage();
}
}
在 OnAuthorization
方法中,您可以获得自定义授权逻辑中可能需要的所有信息,例如 HttpContext
、Controller
名称, Action
名称。您只需从此方法调用您的自定义身份验证逻辑。
您的自定义身份验证逻辑可能如下所示。
public class CustomAuthenticationLogic
{
public static bool IsAccessAllowed(string controller, string action, IPrincipal user, string ip)
{
//
// Your custom logic here
//
}
}
关于c# - 需要了解如何管理我的应用程序中的角色 (ASP.NET MVC3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10472863/