Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Admin rights for a single method

Is it possible to require administrator rights for one single method?

Something like this:

[RequireAdminRightsForThisMethod()]  private void TheMethod(){      // Do something  } 
like image 548
lluismontero Avatar asked Jan 07 '10 16:01

lluismontero


People also ask

What are the rights of an admin?

Having administrator rights (sometimes shortened to admin rights) means a user has privileges to perform most, if not all, functions within an operating system on a computer. These privileges can include such tasks as installing software and hardware drivers, changing system settings, installing system updates.

Why do you need administrator rights on a machine?

Admin rights enable users to delete files on their machine, including system files, user accounts, and even the operating system. The consequences: machine crashes and a subsequent call to the service desk.

How do I remove administrator rights for a specific app in Windows 10?

Right-click on the program's shortcut (or exe file) and choose Properties. Switch to the compatibility tab and uncheck the box next to "Run this program as an administrator". Click "ok".


2 Answers

You can add a PrincipalPermission attribute to your method to demand administrative privileges for its execution:

[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")] public void MyMethod() { } 

This is described in more detail in the following article:

Security Principles and Local Admin Rights in C# .Net

If you are looking for a way to elevate an already existing process I doubt that this is possible as administrator privileges are given on process-level to a process upon startup (see this related question). You would have to run your application "as administrator" to get the desired behavior.

However, there are some tricks that might allow you to do what you want, but be warned that this might open up severe security risks. See the following thread in the MSDN forums:

Launching MyElevatedCom Server without prompting Administrator credentialls from Standard User

Update (from comment)

It seems that if an update requires elevation your application update is best done by a separate process (either another executable, or your application called with a command line switch). For that separate process you can request elevation as follows:

var psi = new ProcessStartInfo(); psi.FileName = "path to update.exe"; psi.Arguments = "arguments for update.exe"; psi.Verb = "runas";  var process = new Process(); process.StartInfo = psi; process.Start();    process.WaitForExit(); 
like image 64
Dirk Vollmar Avatar answered Oct 09 '22 14:10

Dirk Vollmar


A method can require administrative privileges to run, but it's not possible to automatically elevate to Admin when executing a method.

like image 34
SLaks Avatar answered Oct 09 '22 16:10

SLaks