bevacqua
bevacqua

Reputation: 48476

c# Granting "Log On As Service" permission to a windows user

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.

Upvotes: 13

Views: 9430

Answers (1)

Steve Townsend
Steve Townsend

Reputation: 54148

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");
   }
}

Upvotes: 12

Related Questions