我在一个具有许多不同权限和不同角色的大型应用程序中进行了如下操作[我这里没有代码,所以我将尝试在此处重新创建它]:
我首先实现了一个名为 SecuredPage 的类,如下所示:
public class SecuredPage : System.Web.UI.Page
{
// Those Permissions are mandatory, so user needs to have all of them
public List MandatoryPermissions { get; set; }
// Those Permissions are optional, so if the user have at least one of them, he can access
public List OptionalPermissions { get; set; }
protected override void OnLoad(EventArgs e)
{
MyUser loggedUser = (MyUser) this.User;
base.OnLoad(e);
foreach (Permission mandatoryPermission in MandatoryPermissions)
{
// if the user don't have permission, we can redirect him
if (!loggedUser.HasPermission(mandatoryPermission))
{
RedirectToDontHaveAccess();
break;
}
}
bool hasAccessToThePage = false;
foreach (Permission optionalPermission in OptionalPermissions)
{
// If the user has at least one of the permissions, he can access
if (loggedUser.HasPermission(optionalPermission))
{
hasAccessToThePage = true;
}
}
if (!hasAccessToThePage)
{
RedirectToDontHaveAccess();
}
}
private void RedirectToDontHaveAccess()
{
throw new NotImplementedException();
}
}
这将是用户需要访问权限的所有页面的基本页面。
MandatoryPermissions 是用户必须拥有所有这些权限才能访问该页面,OptionalPermissions 是用户至少需要其中一个才能访问该页面的权限。
没有必要在每个页面上都使用两者,因为如果您有 MandatoryPermissions,那么您是否有可选项并不重要。
权限是一个枚举:
public enum Permission
{
// Usually this enum will replicate a domain table from the database
EditUser = 1,
SearchUserByUsername = 2,
SearchUserByEmail = 3
}
而MyUser 是MembershipUser 的实现:
public class MyUser : System.Web.Security.MembershipUser
{
internal bool HasPermission(Permission permission)
{
//
// TODO: Check on database if the user has the permission or not
//
}
}
那么,您在页面中唯一需要做的就是填充权限列表:
public partial class EditUser : SecuredPage
{
protected void Page_Load(object sender, EventArgs e)
{
MandatoryPermissions.Add(Permission.EditUser);
}
}
public partial class SearchUser : SecuredPage
{
protected void Page_Load(object sender, EventArgs e)
{
OptionalPermissions.Add(Permission.SearchUserByUsername);
OptionalPermissions.Add(Permission.SearchUserByEmail);
}
}
好的,搜索示例不是很好,但我想你明白了。
整个想法是在权限验证之前调用base.OnLoad(e);,因此您只需在Page_Load中填写权限即可。
我不确定这是否是最好的解决方案,但我相信它很有帮助:)