I've create a custom attribute for my web pages... In the base page class I've created I'm trying to pull if that attribute has been set. Unfortunately it does not come back as part of the GetCustomAttributes function. Only if I explicitly use the typeof(myclass) to create the class. I have a feeling it's due to how asp.net classes are generated. Anyone have any suggestions on how to get this to work?
namespace SecuritySample.SecurityCode { [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] public sealed class MHCSecurityAttribute : Attribute { private string _permissionSet; private bool _viewable;
public MHCSecurityAttribute(string permission, bool viewable)
{
_permissionSet = permission;
_viewable = viewable;
}
public string PermissionSetRequired
{
get { return _permissionSet; }
}
public bool Viewable
{
get { return _viewable; }
}
}
}
using System; using SecuritySample.SecurityCode;
namespace SecuritySample { [MHCSecurityAttribute("testpermission", false)] public partial class AdminOnlyPage : BasePage, IMHCSecurityControl { protected void Page_Load(object sender, EventArgs e) {
}
public void DisableControl()
{
Server.Transfer("Error.aspx");
}
public void EnableControl()
{
}
}
}
using System.Web.UI.WebControls;
namespace SecuritySample.SecurityCode { public class BasePage : Page { private string _user;
protected override void OnLoadComplete(EventArgs e)
{
base.OnLoadComplete(e);
_user = string.Empty;
if (Session.Contents["loggedInUser"] != null)
_user = Session["loggedInUser"].ToString();
// perform security check
// check page level
if (this is IMHCSecurityControl)
{
System.Reflection.MemberInfo info = this.GetType();
object[] attributes = info.GetCustomAttributes(false);
bool authorized = false;
if ((attributes != null) && (attributes.Length > 0))
{
foreach(MHCSecurityAttribute a in attributes)
{
if ((MHCSecurityCheck.IsAuthorized(_user, a.PermissionSetRequired)))
{
((IMHCSecurityControl) this).EnableControl();
authorized = true;
break;
}
}
if (!authorized)
((IMHCSecurityControl)this).DisableControl();
}
}
}
}
}