SQL Query works in SSMS but not in C#: SELECT denied

0

To begin with: It is not a particular statement that does not work. SELECT * FROM [TABLE]; does not work either. When I run it in SSMS as user A it works perfectly fine. When I use it in C# like this:

string sqlCommand = "SELECT * FROM [TABLE];"

using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Name"].ToString()))
using (var command = new SqlCommand(sqlCommand, conn))
{
    conn.Open();

    using (var dataReader = command.ExecuteReader())
    {
        while (dataReader.Read())
        {
            // work with results
        }
    }
}

I log this code block with a try-catch and I get this error message: System.Data.SqlClient.SqlException (0x80131904): The SELECT permission was denied on the object 'TABLE', database 'MyDb', schema 'dbo'.

Even if I run the program on the server where the db is, I get the same error.

My connection string looks loke this:

Data Source=Server\Something;Initial Catalog=MyDb;User ID=DOMAIN\username;Password=verySecurePassword;Trusted_Connection=True;

User A has the datareader role on the entire db.

Do you have any idea why this might be? My db admins cannot help me either and it does not appear to be a network issue, as the connection seems to work.

c#
sql-server
ssms
sqldatareader
asked on Stack Overflow Nov 20, 2018 by Taysumi • edited Nov 20, 2018 by Joel Coehoorn

1 Answer

5

When you have this in your connection string:

Trusted_Connection=True;

This part of the connection string is ignored:

User ID=DOMAIN\username;Password=verySecurePassword;

Trusted connections and integrated security mean you always connect to the server as the account running your program's process. You don't get to specify the password; instead, the program will pass the authentication token issued for the user running the process, and the database will validate against that token.

If you need to use a domain login, you must run your program as that user. If you need to use a username/password, you must use Sql authentication with a non-domain account defined in Sql Server.

answered on Stack Overflow Nov 20, 2018 by Joel Coehoorn

User contributions licensed under CC BY-SA 3.0