简体   繁体   English

在调试模式下声明安全性

[英]Declaritve Security in Debug Mode

I want to use declarative security to guarantee that my app is only run by a local admin on the machine. 我想使用声明式安全性来确保我的应用仅由计算机上的本地管理员运行。 For example, 例如,

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
    try
    {
        LoadUsers();
    }
    catch (System.Security.SecurityException)
    {
        MessageBox.Show("You must be a local administrator to run this application.");
        System.Environment.Exit(1);
    }
}

// You must be an admin to run this method...
[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]
private void LoadUsers()
{
    // etc.
}

That is all well and good; 一切都很好。 however, it would be nice if I could debug without first launching the IDE with "Run as Administrator". 但是,如果我不先使用“以管理员身份运行”启动IDE就可以进行调试,那就太好了。

Question : Is there a way to get around this in the security declaration attribute? 问题 :在安全声明属性中是否可以解决此问题? Or is there a different security demand I can use? 还是我可以使用其他安全要求? Thanks! 谢谢!

I guess there's more control with Imperative security in this case. 我想在这种情况下,命令式安全性还有更多控制权。 One can see if the debugger is attached or not before making the security demand. 在提出安全要求之前,可以看到是否已连接调试器。

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
        try
        {
            // USE IMPERATIVE SECURITY TO ALLOW THE APP TO RUN IN THE DEBUGGER
            if (!Debugger.IsAttached)
            {
                string user = string.Format(@"{0}\{1}", Environment.UserDomainName, Environment.UserName);
                PrincipalPermission permission = new PrincipalPermission(user, @"BUILTIN\Administrators");
                permission.Demand();
            }
            LoadUsers();
        }
        catch (System.Security.SecurityException)
        {
            MessageBox.Show("You must be a local administrator to run this application.");
            System.Environment.Exit(1);
        }
    }

    // NO DECLARATIVE SECURITY DEMAND HERE
    private void LoadUsers()
    {
       // etc.
    }

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

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