普通的权限验证一般都是写一个方法,然后再执行方法之前检查一下权限
这样做的坏处是每个地方都需要修改加权限验证
而用AOP的方式来做的话就很方便
网上找了一个例子,测试通过,感觉蛮好用的,记录一下[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public class TaskInfo : Attribute
{
public string Name { get; set; }
public string Description { get; set; }
public TaskInfo() { }
public TaskInfo(string name, string description)
{
this.Name = name;
this.Description = description;
}
}
//特性定义,用于 Consumer [AttributeUsage(AttributeTargets.Class)] public class PermissionCheckAttribute : ContextAttribute { public PermissionCheckAttribute() : base("PermissionCheck") { } public override void GetPropertiesForNewContext(IConstructionCallMessage ccm) { ccm.ContextProperties.Add(new PermissionCheckProperty()); } }
internal class SecurityAspect : IMessageSink { private IMessageSink m_next; internal SecurityAspect(IMessageSink next) { m_next = next; } #region -- IMessageSink -- public IMessageSink NextSink { get { return m_next; } } public IMessage SyncProcessMessage(IMessage msg) { Preprocess(msg); IMessage returnMethod = m_next.SyncProcessMessage(msg); return returnMethod; } public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink) { throw new NotImplementedException(); } #endregion #region --自定义的 AOP 方法-- private void Preprocess(IMessage msg) { //只处理方法调用 if (!(msg is IMethodMessage)) return; //获取方法中定义的 Task 属性,交给权限检查类去检查 IMethodMessage call = msg as IMethodMessage; MethodBase mb = call.MethodBase; object[] attrObj = mb.GetCustomAttributes(typeof(TaskInfo), false); if (attrObj != null) { TaskInfo attr = (TaskInfo)attrObj[0]; if (!string.IsNullOrEmpty(attr.Name)) PowerHelper.PermissionCheck(attr.Name); } } #endregion }
public class PermissionCheckProperty : IContextProperty, IContributeObjectSink { #region IContributeObjectSink 实现,将 AOP 类加入消息处理链 public IMessageSink GetObjectSink(MarshalByRefObject o, IMessageSink next) { return new SecurityAspect(next); } #endregion #region IContextProperty 实现 public string Name { get { return "PermissionCheckProperty"; } } public void Freeze(Context newContext) { } public bool IsNewContextOK(Context newCtx) { return true; } #endregion }
public class PowerHelper { public static void PermissionCheck(string taskName) { if (HttpContext.Current != null) { //此处做权限验证 //用户,角色等自由操作 if (HttpContext.Current.Session["user"] != null && HttpContext.Current.Session["user"] == "ysuhy") { //拥有权限,正常 } else { //没有权限 throw new UnauthorizedAccessException("访问被拒绝,当前用户不具有操作此功能的权限!"); } } } }
普通业务类方法 [PermissionCheck()] public class ItemManager : ContextBoundObject { [TaskInfo("AddItem", "增加")] public void AddItem() { Console.WriteLine("执行增加"); //... } }
调用protected void Page_Load(object sender, EventArgs e) { Session["user"] = "ysuhy"; ItemManager itemManager = new ItemManager(); itemManager.AddItem(); }