Let us start by stating the obvious: password management for programs and services is a huge pain for developers.
It’s one of the things that is always overlooked during development, where you’re just trying to make the thing work. It’s even not given much attention during testing, where people are usually focused on whether it works correctly on normal uses and edge cases, they look for the UI and usability etc etc.
But come deployment time and the admins start complaining. Storing passwords in plain text files is, how to put it mildly, BLOODY HORRIBLE from a security perspective. And storing them in better ways takes a surprising amount of time –just when the devs thought they’re almost finished.
So having less passwords to store and secure is very helpful for everyone. And one thing many applications need is the credentials to a database.
Fortunately, if your application is running as a Windows service and your database is SQL server, you don’t need a password. You can use integrated security. All you need is to allow (grant) access for the service user to read data from SQL server.
Now here’s the thing: if you’re using a domain user to run the server, that’s obvious. You just create the user in SQL and grant access as needed (you can even use the script below and change the user). But what happens when, as is very common, the application is running under the Local System account?
Turns out, fortunately, there’s a solution for that as well. Every computer’s Local System account exists in Active Directory as “hostname$”. E.g. if the hostname of the application server is MYSERVER, the user name will be MYDOMAIN\MYSERVER$.
So you can run the following SQL to grant access:
/* Source: DotJim blog (http://dandraka.com) Jim Andrakakis, April 2023 */ -- suppose you work on domain MYDOMAIN -- and the server that hosts the Windows -- service is MYSERVER -- this is the name given by the hostname command USE mydatabase; GO CREATE LOGIN [MYDOMAIN\MYSERVER$] FROM WINDOWS; GO CREATE USER [MYDOMAIN\MYSERVER$] FOR LOGIN [MYDOMAIN\MYSERVER$] GO /* db_datareader grants read-only access */ ALTER ROLE [db_datareader] ADD MEMBER [MYDOMAIN\MYSERVER$] GO /* if you want to insert, update or delete, add db_datawriter */ ALTER ROLE [db_datawriter] ADD MEMBER [MYDOMAIN\MYSERVER$] GO
That done, you can use the following connection string to connect to the database:
or if you’re running a named instance: