C# • Secure Your Database Connection String

Listing 4. The key requirement for securing your database connection string is to avoid exposing your database connection string (or your connection credentials). Once you create the class, deploy it to the GAC and add a reference to it in your application.

using System.Data.SqlClient;
using System.Security.Principal;

namespace MyConnectionString
{
	public class DBConnection
	{
	public SqlConnection Get()
		{

// Check here to see if this is a valid request
// Use your own business logic
			if (false)
			{
				return null;
			}

// Or use the Windows identify to see if the 
// caller matches the list of user ids that CAN 
// access this class. Make sure the caller was
// authenticated 
			WindowsIdentity CallersIdentity = 
				WindowsIdentity.GetCurrent();
			if (CallersIdentity.IsAuthenticated == 
				false)
			{
				return null;
			}

// Code to get the connection string from a config
// file or a separate database. This is merely a
// sample to make the code work -replace this with 
// your business logic
			string myConnectionString = 
				"Initial Catalog=Northwind;Data 
				Source=localhost;Integrated 
				Security=SSPI;";

// Now go get a database connection and return it
			SqlConnection myConnection = new
				SqlConnection( 
				myConnectionString);
			return myConnection;
		}
	}
}