Search code examples
sql-serverauthenticationwindows-services

SQL "login failed for user [username]" error for windows service, but SSMS login works


I'm writing a windows service that needs to connect to a SQL server to retrieve some information. However, the server doesn't allow me to connect: login failed for user [domain/username]. The strange part is that everything works totally fine from inside SSMS. I can log in, query the database, and everything works out perfectly. It's only through the windows service that it's throwing that error.

For reference, here's the connection string I'm using:

Data Source=sqlserveraddresshere;Initial Catalog=databasenamehere;User ID=domain\username;Password=password`

I doubt that this is related, but when I try to use Integrated Security it's getting my computer name instead of my own user name. I'm 99% sure this is because our anti-virus and monitoring software is spoofing an administrator user on top of my windows session to do its job. In any case, just entering the correct username and password should be working regardless, right?

I took a look at some other questions involving the same error, but they were all unrelated. From what I can tell everyone who can get in through SSMS can access their SQL server through code, too. This is the most similar question I could find, although it didn't help much: Can't connect to SQL Server: "Login failed for user "."

Also, before you ask, I HAVE ALREADY CHECKED FOR TYPOS. Actually, I've even tried to use other user's accounts to make sure there wasn't something funky going on with my permissions. If you need me to post any code let me know. Thanks for your help!

UPDATE:

I changed the account for the service and switched back to IntegratedSecurity = true. It seems like something has changed, because now I'm receiving a slightly different error:

Cannot open database "mydatabase" requested by the login. The login failed. >Login failed for user 'MYDOMAIN\myUserName'.


Solution

  • It's working! Finally!

    First, using Kevin's suggestion (comment underneath the original question), I checked through the SQL Server Logs (in Management Studio, expand server, expand Management, expand SQL Server Logs). This is how I found more lengthy error reporting that helped me diagnose the issue.

    Turns out the server didn't allow anything other than Windows Authentication, so that's why my attempts at entering the UN/PW manually failed.

    However, I still had the issue where the server was passing my machine name as the user instead of my username. This was fixed with Duncan's suggestion of changing the user that the service ran under to my name (right click in Services->Properties->Log On Tab).

    Thanks to everyone for your help, much appreciated.