0

I'm trying to implement a security mechanism to automatically test a particular plugins permissions and method security privileges and I've gotten a bit stuck on how to get this working.

I've writing a custom MEF Metadata attribute that takes a constructor property like:

params PluginPermission[] permission

This contains an array of all the permissions that the plugin is granted.

The PluginPermission class looks like:

PluginPermission.cs

public enum PluginPermission
{
    CreateUsers,
    DeleteUsers,
    ReadPassword,
    WritePassword,
    AddUsersToGroups,
    AddGroups,
    DeleteGroups
}

I've also written a RequiredPermissionAttribute that targets individual methods and takes one or more PluginPermission objects to tell the system what permissions are required for an individual method to be execute. These are applied to the interface for the plugins like:

 ILicensingManagement.cs

 [RequiredPermission(PluginPermission.CreateUsers)]
 bool AddUser(string userName);

Obviously if the plugin doesn't have the required permissions for a particular method the method is not executed.

What I'm stuck on is how to actually get the test method in the RequiredPermissionAttribute class to run before the method is executed and how to gracefully exit the execution if the permissions requirements for the method are not met by the plugin.

I looked at the xUnit BeforeAfterTestAttribute but the implementation seemed so specific I stuggled to pull the source code apart to arrive at the solution.

4

1 回答 1

0

我无法评论 MEF 特定的事情,但要记住一件事,自定义属性只不过是“标签”,除非您的代码专门检查它们,否则它们不会做任何事情,例如使用反射。

xUnit的BeforeAfterTestAttribute可能有效,因为 xUnit 使用反射来执行方法。当它遇到这个属性时,它会相应地改变它的行为。

.NET 框架命名空间中的属性之所以有效,是因为 CLR 会检查它们,或者编译器会检查它们。

我知道这并不能真正完全回答您的问题,但是发表评论有点太长了。

更新:您可以使用Typeif 它是一个类或MethodInfoif 它是一个方法来访问属性,例如

MethodInfo mi = /* method info */;
Attribute[] attrs = mi.GetCustomAttributes(typeof(RequiredPermissionAttribute), false);
RequiredPermissionAttribute req = attrs.Cast<RequiredPermissionAttribute>().FirstOrDefault();

if ((req != null) && (/* current user does not have the required permission */)) throw new Exception();

但这并不是真正的安全解决方案,开发人员可以轻松避免这些检查。我只是简单地看了一眼,但 PostSharp 或许可以帮到你。

于 2013-04-18T11:19:13.850 回答