ePe*_*man 6 c# asp.net roles roleprovider asp.net-mvc-3
我正在开发一些网站,这是一种在线工作场所,会有一些用户和一些正在进行的计算机编程项目,每个用户可以有多个角色,例如一个特定用户可以是项目的项目经理和开发人员为另一个项目.自然地,项目经理比项目中的开发人员拥有更多的权限.我的问题是如何在我的代码中整齐地管理这个?我打算使用我的自定义角色提供程序并使用Authorize属性,但这还不够,因为我需要项目Id和用户ID来查找用户在特定项目中的角色.
首先,你需要为扩展角色管理创建额外的表,projects以及与users上下文的关系operations,这可能是你的controller's actions.
一种方法是创建自己的表roles.在这种情况下,您将只使用Asp网membership users,但这一切都取决于您的要求.
其次,您必须处理它.MVC在我看来,最好的方法是通过您自己的自定义Authorization属性实现它,并使用您的自定义授权属性而不是属性来装饰控制器的操作[Authorization].
它非常简单.
[CustomAuthorize]
//[Authorize]
public ActionResult GetProjectTasks(string projectname)
{
}
Run Code Online (Sandbox Code Playgroud)
为此,你必须从中固有你的类,FilterAttribute并且还必须实现IAuthorizationFilter接口.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
在该方法中OnAuthorization,你可以得到所有你可能在你的自定义授权逻辑等所需要的信息HttpContext,Controller姓名,Action名称.您必须从此方法调用自定义身份验证逻辑.您的自定义身份验证逻辑可能如下所示.
public class CustomAuthenticationLogic
{
public static bool IsAccessAllowed(string controller, string action, IPrincipal user, string ip)
{
//
// Your custom logic here
//
}
}
Run Code Online (Sandbox Code Playgroud)