C# – Application connecting to database server

cdatabaseSecurity

I'm working on an application which requires user credentials and so on. So a database is required on the backend.

What is the best practice to connect to a database without hardcoding your password into it? The program could be reverse engineered and one might get the password which is something we obviously don't want.

Best Answer

I just went though this myself. Assuming you're using SQL Server, I actually created user accounts on the database server for every user (you can do this from t-sql). I have one general user account that I can use to first verify that I can make a connection, and select from a Version table that makes sure the version of the software running matches the database schema version.

Users who have the ability to add/remove users in the application also need to have rights to administrate users on the database server. This is actually a problem since the users are defined at the database server level, not at the database level. That means someone with the ability to add/remove database server users could potentially create a new user that could access another database. For this reason, I suggest running a separate instance of the database server for this.

There are other ways to go about it:

  • If your users login to Windows with unique accounts, you can use integrated security where they just authenticate with the Windows credentials. Ideal if it works for you (we had some shared computers, so it didn't).
  • You can have a common user and hard-code the credentials in the connection string, but only give that user access to stored procedures, not tables. Then in the stored procedures you have to pass login credentials every time, and the stored proc does the authentication. This has the advantage of allowing more granular security (you can limit what rows they can get back, so for instance, they wouldn't be able to see another user's timesheet records, but they could see their own).
  • If you need only rudimentary protection of some data, just have two users: NormalUser and AdministratorUser. Only store the NormalUser's password in the connection string. When you need to do something that requires administrator level permissions, have them enter the AdministratorUser's password, and open a new connection.
  • Put the database into local-only mode (no remote connections) and create a web service that runs on that machine and acts as your data access layer. This will let you do really advanced security (gives you full control over what a user can see) and it means the rest of your application basically sees the data as business objects rather than rows and columns. The web service, obviously, needs to handle the authentication.
Related Topic