views:

61

answers:

2

how do I grant a user the LogOnAsService right for a service?

I need to do this manually, in the services.msc app I can go to the service, change the password (setting the same that there was before), click apply and I get a message:

The account .\postgres has been granted the Log On As Service right.

How do I do this from code, because otherwise I have to give this permission by hand each time I run the application and this is not a possibility

@Steve

    static void Main()
    {
        // irrelevant stuff

        GrantLogonAsServiceRight("postgres");

        // irrelevant stuff
    }

    private static void GrantLogonAsServiceRight(string username)
    {
        using (LsaWrapper lsa = new LsaWrapper())
        {
            lsa.AddPrivileges(username, "SeServiceLogonRight");
        }
    }

and the LSA lib by this guy Willy.

A: 

I believe this link will help you out.

http://msdn.microsoft.com/en-us/library/ms677116(v=VS.85).aspx

sebastian
+1  A: 

See Granting User Rights in C#.

You have to invoke the LSA APIs via P/Invoke, and that URL has a reference to a wrapper class that does that for you. So the code you end up with is simple:

private static void GrantLogonAsServiceRight(string username)
{
   using (LsaWrapper lsa = new LsaWrapper())
   {
      lsa.AddPrivileges(username, "SeServiceLogonRight");
   }
}
Steve Townsend
sounds great, but I get Win32UnhandledException: The parameter is incorrect
Nico
@Nico - what does your code look like?
Steve Townsend
read my update @original post
Nico
@Nico - where inside the LSAWrapper do you get the exception? Can you use 'domain\\name' instead?
Steve Townsend
No mapping between account names and security IDs was done, anyways I was getting the Sid, the exception was at the end of the AddPrivileges() function: throw new Win32Exception(Win32Sec.LsaNtStatusToWinError((int)ret));
Nico