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...
[PrincipalPer开发者_Go百科mission(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".
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.
}
精彩评论