Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the SqlConnection,Credentials property

So i have a login page and i have to implement a validation: 'If the user is "sa" then it should connect to the Database using that users credentials', which means i have to modify the credentials of my SqlConnection object:

        if(username.Equals("sa", StringComparison.OrdinalIgnoreCase))
        {
            var securePassword = new System.Security.SecureString();
            foreach(char character in password)
            {
                securePassword.AppendChar(character);
            }

            securePassword.MakeReadOnly();
            var credentials = new SqlCredential(username, securePassword);
            sqlConn.Close();
            sqlConn.Credential = credentials;

            sqlConn.Open();

            return true;
        }

But im getting an exception in sqlConn.Credential = credentials; even though the property is not readonly

InvalidOperationException: Cannot use Credential with UserID, UID, Password, or PWD connection string keywords.

Is there any other way to change the Credentials property?

Thanks in advance.

like image 752
DCruz22 Avatar asked Dec 06 '25 10:12

DCruz22


2 Answers

SqlConnection.Credential Property

From https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.credential(v=vs.110).aspx

An InvalidOperationException exception will be raised:

  • If Credential is set on an open connection.
  • If Credential is set when Context Connection=true.
  • If Credential is set when Integrated Security = true.
  • If Credential is set when the connection string uses Password.
  • If Credential is set when the connection string uses UserID.
like image 171
kirodge Avatar answered Dec 07 '25 23:12

kirodge


Or you could use SqlConnectionStringBuilder,

string connectString = "Data source=.;initial catalog=yourDB; 
                        User Id=user; Password=password";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder (connectString);
SqlConnection sqlConn= new SqlConnection(builder.ConnectionString);

Then in your method,

 builder.Remove("User Id");
 builder.Remove("Password");
 // builder.Remove("integrated security"); if you had used
 sqlConn.ConnectionString = builder.ConnectionString;
like image 29
Mike Debela Avatar answered Dec 07 '25 22:12

Mike Debela



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!