简体   繁体   English

在运行时请求程序集的CAS安全设置-C#.NET 2.0

[英]Requesting the CAS Security Settings for an assembly at runtime - C# .NET 2.0

how can I check the security setting of a loaded assembly at runtime with C# .NET 2.0 (VS 2005)? 如何使用C#.NET 2.0(VS 2005)在运行时检查已加载程序集的安全性设置? I'm loading the assembly with: 我正在用以下方式加载程序集:

Assembly externalAssembly = Assembly.LoadFrom(path); 程序集externalAssembly = Assembly.LoadFrom(path);

May be the path is local or it is a remote UNC Path (Network path). 路径可能是本地路径,也可能是远程UNC路径(网络路径)。

If it is a remote network path, the user should set the CAS to "fulltrust" with caspol.exe, to run the application correctly. 如果它是远程网络路径,则用户应使用caspol.exe将CAS设置为“ fulltrust”,以正确运行该应用程序。 How can I check this at runtime, if CAS was configured right? 如果CAS配置正确,如何在运行时进行检查?

I've seen, .NET 4.0 provides a "IsFullyTrusted" property for this purpose. 我已经看到,.NET 4.0为此提供了“ IsFullyTrusted”属性。

Unfortunately I still have to use VS 2005 for my project. 不幸的是,我仍然必须在项目中使用VS 2005。

Regards Tom 问候汤姆

Try this: 尝试这个:

public static bool IsFullyTrusted()
{
    try
    {
        new PermissionSet(PermissionState.Unrestricted).Demand();
        return true;
    }
    catch (SecurityException)
    {
        return false;
    }
}

After I did some homework and dug into Code Access Security a little bit, I hope, I have found a solution for me so far. 我做了一些功课并深入研究了代码访问安全性之后,我希望到目前为止,我已经找到了解决方案。 I need only two lines of code: 我只需要两行代码:

Assembly externalAssembly = Assembly.LoadFrom(path);

// Retrieve the permission set of the external assembly
PermissionSet permSet = SecurityManager.ResolvePolicy(externalAssembly.Evidence);
if(!permSet.IsUnrestricted())
{
    throw new Exception("Assembly is not fully trusted!");
}

If the assembly has the unrestricted permission, IsUnrestricted() returns true, and the collection of permissions in permSet is empty. 如果程序集具有不受限制的权限,则IsUnrestricted()返回true,并且permSet中的权限集合为空。

If it is restricted, false is returned, and the permSet lists the permissions, that were assigned to the assembly by the .NET policy resolution. 如果受限制,则返回false,并且permSet列出由.NET策略解析分配给程序集的权限。

Hope this helps someone in future 希望这对以后的人有帮助

Tom 汤姆

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM