Programmatically determine if the Connection String Uses Integrated Security or Not

Sometimes it is necessary to find out if a connection to the database is using integrated security or not. A simple way to do this is to use the SqlConnectionStringBuilder class to read a connection string from the web.config file. Here’s how it works. Add two connection strings to your web.config file:

<connectionStrings>
<
add name="NorthwindConnectionStringWindowsUser"
connectionString="Data Source=malcolm-pc\sqlexpress;
Initial Catalog=Northwind;Integrated Security=True
"
providerName="System.Data.SqlClient" />
<
add name="NorthwindConnectionStringSqlUser"
connectionString="Data Source=malcolm-pc\sqlexpress;
Initial Catalog=Northwind;User ID=user1;Password=password;
"
providerName="System.Data.SqlClient" />
</
connectionStrings>

Both are connecting to the same database but one is using integrated security, the other is using SQL authentication. By using the ‘SqlConnectionStringBuilder’ class you can find out different information about the connection string. Add references to the System.Data.SqlClient and System.Configuration namespaces. One of the properties you can check is the IntegratedSecurity property as demonstrated below:

C#

SqlConnectionStringBuilder con =
new SqlConnectionStringBuilder
(ConfigurationManager.ConnectionStrings
["NorthwindConnectionStringSqlUser"].ConnectionString);
Response.Write("Integrated security = " + con.IntegratedSecurity);

VB.NET

Dim con As New SqlConnectionStringBuilder _
(ConfigurationManager.ConnectionStrings _
("NorthwindConnectionStringSqlUser").ConnectionString)
Response.Write("Integrated security = " & con.IntegratedSecurity)

The result of the above code is false as it is using SQL authentication:

Integrated security = False

But if you change the connection string to windows authentication the result is different:

C#

SqlConnectionStringBuilder con =
new SqlConnectionStringBuilder
(ConfigurationManager.ConnectionStrings
["NorthwindConnectionStringWindowsUser"].ConnectionString);
Response.Write("Integrated security = " + con.IntegratedSecurity);

VB.NET

Dim con As New SqlConnectionStringBuilder _
(ConfigurationManager.ConnectionStrings _
("NorthwindConnectionStringWindowsUser").ConnectionString)
Response.Write("Integrated security = " & con.IntegratedSecurity)

The result of the above code is true as it is using integrated security:

Integrated security = True






About The Author

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET and regular presenter at conferences and user groups throughout Australia. Being an ASP.NET Insider, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with JavaScript. He also blogs regularly at DotNetCurry.com. Follow him on twitter @malcolmsheridan

No comments: