Save SQL Server Login savely in code (C#)

80 views Asked by At

I'm a fairly new developer and am currently working on a C# program that connects to a MYSQL Server with the following Code:

    class MySql
{
    private MySqlConnection connection;
    private string server;
    private string database;
    private string uid;
    private string password;

    //Constructor
    public MySql()
    {
        Initialize();
    }

    //Initialize values
    private void Initialize()
    {
        server = "mydomain.com";
        database = "dbName";
        uid = "Username";
        password = "Password";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" +
        database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";

        connection = new MySqlConnection(connectionString);
    }

    //open connection to database
    private bool OpenConnection()
    {
        try
        {
            connection.Open();
            return true;
        }
        catch (MySqlException ex)
        {
            //When handling errors, you can your application's response based 
            //on the error number.
            //The two most common error numbers when connecting are as follows:
            //0: Cannot connect to server.
            //1045: Invalid user name and/or password.
            switch (ex.Number)
            {
                case 0:
                    MessageBox.Show("Cannot connect to server.  Contact administrator");
                    break;

                case 1045:
                    MessageBox.Show("Invalid username/password, please try again");
                    break;
            }
            return false;
        }
    }

    //Close connection
    private bool CloseConnection()
    {
        try
        {
            connection.Close();
            return true;
        }
        catch (MySqlException ex)
        {
            MessageBox.Show(ex.Message);
            return false;
        }
    }

Now I'm not quite sure how to securly save the server logins. As you see, in my code, domain, username and Password are just openly in the code.

And as far as I know, that shouldn't be that way.

How can I correct that? Or is it save to store it like that? Thanks!

1

There are 1 answers

5
Gabriel Luci On BEST ANSWER

In .NET, connection strings are normally stored in the .config file for the application (web.config for ASP.NET, app.config for desktop). An example of a MySQL connection string in a config file would look something like this:

<connectionStrings>  
  <add name="MySqlConnectionString"
   providerName="MySql.Data.MySqlClient"
   connectionString="server=127.0.0.1;uid=root;password=bpdash;database=sample" />
</connectionStrings>

Then there are supported methods of encrypting that section of the config file. Both using connection strings and encrypting them are discussed in this Microsoft article: Connection Strings and Configuration Files