Within my startup, I load a set of database connection strings from the appsettings.json file. The connection strings look as follows
"CoreConnectionString": "Server=localhost; Database=DBCore; Uid=someUserName; Pwd=somePW",
"IdentityConnectionString": "Server=localhost; Database=DBAuth; Uid=someUserName; Pwd=somePW"
What is the best way to encrypt this information so I don't show the actual user name and password?
Here's two suggestions to not expose your DB Password and Conn Strings:
Use a secret file in your computer, apart from your Solution. In Visual Studio 2022 you can do it by clicking your project. Just throw your connections strings there like in AppSettings.json.
Pro: Easy to use
Con: You can't deply it with your project or store it at github
Use Azure Key Valut to store all connection strings. Read this doc from Microsoft if it's your way to go.
Pro: No need for local files. Cloud stored Keys.
Con: Need a bot more configuration in your project and an Azure account.
Related
I have a web form developed in ASP.NET and C#. I am storing the connection string to a database in the web.config file like this:
<connectionStrings configSource="MySecrets.config" />
This points to a local file in the same directory as the solution. Debugging locally works, however it is not advisable to commit this file to source control to avoid exposing these secrets.
This article mentions that it is possible to store connection strings on Azure - in the Configurations section of an App Service. The article also says that it's possible to retrieve the connection strings in the code by doing:
dbConn = System.Configuration.ConfigurationManager.AppSettings("myConnStringName")
The article also mentions that "if the application setting(s) happen to already exist in your web.config file, Windows Azure Web Sites will automatically override them at runtime using the values associated with your website. Connection strings work in a similar fashion.
(This assumes that your connection strings are explicit in the web.config file, and if committed to source control, they would be exposed.)
However, in my code, I already have a line with:
dbConn = WebConfigurationManager.ConnectionStrings["myConnStringName"].ConnectionString
Questions:
1) How am I supposed to reconcile these two lines without declaring the same variable (dbConn) twice?
2) How can I not commit MySecrets.config to source control, but at the same time use it when I debug my app locally, while using the connection string stored on Azure when working with the published app?
I have a C# windows form application and I connect it to the SQL server in my computer. Now I going to deliver the software to a user. So, what can I do to change the connection string to the user SQL server? Is there any way to do the connection string computer independent? Kindly help me
Regards.
I'm assuming you're hard-coding connection strings into your code. You need an application config file.
Or you could use connection string like this (if database (SQL server) is on same machine as app using it and database name is the same) :
Server=localhost\instanceName;Database=myDataBase;User Id=myUsername;Password=myPassword;
instanceName could be "nothing" (default instance) or named instance (SQLEXPRESS).
Or do it as #Xavier J suggested - store connection string in app config or INI file.
application config files are one idea, but because they are managed through the IDE means have to change manually for deployment.
Better to use the registry (cleaner too - no need to post-edit the file), and the installer can get conditional on where it's deployed, alternatively ask the user during installation, skip if the registry entry already exists.), confirm the connection string at install time. database path/host/name exists...
You can store it in the app.config of your project. Then if you wanted the user to give credentials you could make a form and save the string to the value of that configuration.
<appSettings>
<add key="connectionString" value="Connection string goes here"/>
</appSettings>
Then call it and set it using the ConfigurationManager
ConfigurationManager.AppSettings["connectionString"] = "Your Value";
Or you could just replace the connection string yourself in the file once its on the users computer
After I deployed my mobile service to Azure, calls to the service fails because of this error:
No connection string named 'ApplicationEntities' could be found in the application config file.
The error only occurs on Azure side. When I test the service locally, the connection to the remote database works without a problem.
I separated my solution into several projects:
Web Api
Business Logic
Data Access (contains the DbContext, database first)
Common (contains the entities generated by EF)
As I always do, I copied the connection string generated in my app.config of the DataAccess Assembly into the connectionStrings-Element of my web.config (Web Api project).
<connectionStrings>
<add name="ApplicationEntities" connectionString="<the connection string>" providerName="System.Data.EntityClient" />
</connectionStrings>
In the web deploy settings, I selected the connection string for "ApplicationEntities". I tested it with and without the option "Use this connection string at runtime (update destination web.config). I always get the same error.
Then I got curious and logged the connection strings available via the ConfigurationManager with something like this:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
{
sb.AppendLine(ConfigurationManager.ConnectionStrings[i].ConnectionString);
}
trace.Info(sb.ToString());
I got two connection strings:
data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
Data Source=theserver.database.windows.net;Initial Catalog=thedb_db;User ID=theuser;Password=thepassword;Asynchronous Processing=True;TrustServerCertificate=False;
The username and password is strangely different from the username and password stated in the management portal.
Also the EF-Metadata information get lost.
I get this connection strings when testing locally:
data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
metadata=res://*/DataContext.ApplicationEntities.csdl|res://*/DataContext.ApplicationEntities.ssdl|res://*/DataContext.ApplicationEntities.msl;provider=System.Data.SqlClient;provider connection string=\"data source=theserveraddress,1433;initial catalog=thedb_db;persist security info=True;user id=theusername;password=thepassword;MultipleActiveResultSets=True;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;App=EntityFramework\"
I expect to get the same connection strings when running on Azure. Any idea what's going wrong?
Update:
I just went for remote debugging the service (see here). As I opened the downloaded publish-profile in my text editor, I discovered that there is an attribute SQLServerDBConnectionString - containing the connection string that always gets forced when deployed - with the same username and password I'm not aware of that it exists.
I tried to overrwite this connection string but it did not help. That connection remains the active.
Update 2 / May 29th 2014:
Seems that in the meantime the error has been fixed by the azure mobile team. Still running the same code using the database first approach and it's working now. Thanks a lot!
I have myself tried using DB first approach with dot net backend mobile services & ran into same sort of problems as you. Digging around further, following is my observation :
The azure mobile service with dot net backend must use code first approach only. This generates a specialised connection string with metadata (starting with res:)
The name of the connection string has to be the same as it is when you download the default sample todo app I.e. Ms_TableConnectionString.
There is an option in azure websites to select custom SQL provider to help make a custom connection string, this option, however, is not available for dot net backend mobile service in Azure Management portal.
P.s. Posting as answer because I don't have a enough points to comment..
Just wanted to give an update that I have been looking at this for some time and think I for the first time see it too. I don't know what is going on but wanted to let you know that we are indeed looking at it.
Henrik
(I don't have enough points to comment so having to do this as an answer)
Henrik, I have this same problem. If I ftp on to the box I can see that the web.config has the correct connection string but it fails as trying to use the username in the SQLServerDBConnectionString property (OoWUqr****Login). Is it possible you could let me know in what order it is looking for connection strings and where?
And if it can't stop it using the other user is there a way I can permission them for the correct database through mobile services?
Thanks
F
I am continuing my previous question, as the reply lead to further doubts/points/concerns. I need help with the connection string on the web host server.
My connection string in the local computer is:
string connectionString = "Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\data.mdf;Integrated
Security=True;User Instance=True";
Now, I simply used the website copy tool with the VS 2010, and the entire website is copied as it is on the web host, with the database being at domainName/httpdocs/Experiment/App_Data/data.mdf
Now, I don't know how the complete connection string on the web hosting server look like. Some of the things which I learned, on the basis of those, I guess it should be:
string connectionString = "Data
Source=IP_Address_Of_WebHostingServer;AttachDbFilename=|DataDirectory|\data.mdf;User
ID=XXXX;Password=XXXX;User Instance=True";
Is it right (or COMPLETE?)? Also, I have no clue what the user id or password is? So on local computer, with the help of Integrated Security=True the windows authentication was being made. How to do it on the remote web host?
In the webhosting console, I see features such as create database, create database users, I can see the username and password aspects there. If those are required then how do I connect that with the database I just copied? It seems like those are the one's where database is created from scratch, while I already have the *.mdf (database) uploaded/copied.
I am stuck at this stage, and have no clue on how to proceed further. I know its something trivial, but out of scope of my knowledge. Please help me in completing the connection string. How do I make the database (data.mdf) file reachable/accessible?
I came across some articles which told to import the database and such (but where/why?), but I don't get it. When the database is in the App_Data folder, then why/how do I do that?
I am confused, please help.I'll highly appreciate step-by-step approach to fix it.Thanks.
EDIT (solution):
The solution given below is perfect. Apart from that this website/blog is worth checking.
-- http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/asp-net-hosting-options-cs
And if you don't have SQL Management Studio, best way to install is instructed here:
-- http://blogs.msdn.com/b/bethmassi/archive/2011/02/18/step-by-step-installing-sql-server-management-studio-2008-express-after-visual-studio-2010.aspx
Step 1 - Create a DB Script from SQL Management Studio
You will need to firstly script off you database schema and data (not as scary as it sounds - follow the steps here http://blog.sqlauthority.com/2011/05/07/sql-server-2008-2008-r2-create-script-to-copy-database-schema-and-all-the-objects-data-schema-stored-procedure-functions-triggers-tables-views-constraints-and-all-other-database-objects/ ) .
Step 2 - Create your DB at HostGator and Import your DB Script
Create your database at HostGator and import your script file (Follow this guide here http://support.hostgator.com/articles/plesk/plesk-9/how-to-create-or-import-databases-plesk-9 ).
Step 3 - Update your connection string and deploy!
You'll need to update your connection string to be something like this (you will need to add your details).
<add name=”CRMConnectionString” connectionString=”Data Source=Server IP;Initial Catalog=DBName;User ID=UserName;Password=Pwd;” providerName=”System.Data.SqlClient”/>
This connection string was cribbed from this resource here http://asoftwaredeveloper.wordpress.com/2012/01/06/hostgator-web-hosting-and-mssql-db-access/
Then publish your website and upload your files. Its worth noting that you won't need to update your App_Data folder and its contents when you publish because you'll be pointing at the DB on their server not the one in your directory.
I'm here for a trouble with SQL Server CE in a C# application.
This is a really simple question, at first I was trying to do an INSERT into a table, but it didn't do it, so I searched and the solution was to put the literal string to connect to the database.
try
{
cnTrupp.Open();
SqlCeCommand com = new SqlCeCommand("INSERT INTO tipo_venta(nombre) VALUES (#nombre)", cnTrupp);
com.Parameters.AddWithValue("#nombre", pNombre);
com.ExecuteNonQuery();
com.Dispose();
}
catch (SqlCeException e)
{
LogFile log = new LogFile(e.Message);
}
finally
{
cnTrupp.Close();
}
After that with the literal string, I was wondering, when I deploy the app, how I'm supposed to change that connection string? so it points to the actual database in the new computer
The comments on "Paul Sasik"'s post talk about the Data Source=|DataDirectory|\example.sdf entry in the app.config file of your application.
For the sake of completeness: This |DataDirectory| part is a macro that expands automatically to the folder where your application is running and should not be hardcoded. If you want to change the folder, you may use the following line in Program.cs:
AppDomain.CurrentDomain.SetData("DataDirectory", <New Folder>);
At least this is true for desktop applications. As mobile applications (in VS 2005 and 2008) don't support the same configuration mechanism, you have to create the connection string manually there.
Make use of the .NET app.config file. This is a VB article but will get you started.
.NET config files are fairly easy to work with but with information like a db connection, you might want to consider encrypting the string in the config file. Or at least the password. That is if security is a concern. Many times it's not. Especially on mobile devices which are inherently unsecure (at least in the WinCE world... up to CE5 v.6)