| Details | ![]() |
| QuickDocId | 395 |
| Written by | Imar Spaanjaars |
| Posted | 06/04/2006 00:12 |
| Page views | 111379 |
| Listened to | Take One (Re-built) by Front 242 (Track 16 from the album: Geography 2) |
Are you looking to hire an experienced software developer or .NET consultant? Then get in touch with me through my company's web site at devierkoeden.com
Found an interesting article on this site? Got inspired by something you read here? Then consider making a donation with PayPal.
Configuring an ASP.NET 2 application to work with SQL Server is not an easy undertaking. You need to be aware of a number of security related concepts in the area of SQL Server, IIS and ASP.NET 2.0. The number of different options you have make the problem even more complex. In this article, I describe some of the common scenarios that you are likely to run into when working with SQL Server and ASP.NET pages. I'll be using SQL Server 2005 in all my examples, but most of the concepts also apply to SQL Server 2000. Note that most of the principles described in this article can also be used in ASP.NET 1.x applications.
Many books about ASP.NET 2.0 (including my own), use Microsoft SQL Server 2005 Express Edition. The reason behind this choice is that the Express Edition is very easy to use and configure. In many cases, using a SQL Server Express database is as easy as adding a database to your project (or one of the new Login controls), and then hitting F5 to run the application. This makes the Express Edition great for local development and quick and dirty applications. However, in a production environment, the Express Edition won't cut it. Instead, you'll need one of its bigger brothers like SQL Server 2005 Standard Edition. But as soon as you try to make the move to one of these SQL Server versions, you may run into a number of security related configuration issues. This article takes a look at a number of common issues that you need to be aware of when you try to use SQL Server 2005 in your applications.
The article starts off with familiarizing you with the terminology that you'll run into when configuring the system. The second part then looks at a number of different scenarios for configuring an ASP.NET 2.0 application with SQL Server 2005. You'll see how to use a custom SQL Server database in your own application and how to configure both SQL Server and your application.
This article doesn't touch on configuring your database for the new ASP.NET 2.0 provider features, like Membership and the Role Manager. However, there's a great article by Scott Guthrie called "Configuring ASP.NET 2.0 Application Services to use SQL Server 2000 or SQL Server 2005" that shows you how to use tools like aspnet_regsql.exe to configure an existing SQL Server 2000 or 2005 to work nicely with the new provider features. That article, together with this one, should provide you with enough details to set up your system so it can work with a SQL Server 2000 or 2005 database.
When you want to connect to a SQL Server database, you have to authenticate yourself, so the database knows what user is trying to gain access. Microsoft SQL Server supports two different authentication mechanisms: SQL Server Authentication and Windows Authentication (often called Integrated Security).
With SQL Server Authentication, SQL Server takes care of user management. This means that users and their passwords are managed by SQL Server. You can access the user management functionality in SQL Server through the SQL Server Management Studio (for SQL Server 2005) or the Enterprise Manager (for SQL Server 2000). You'll see more on this later.
To connect to a SQL Server instance that uses SQL Server authentication, you need to pass a user name and password in the connection string of your application. A typical connection string looks like this:
Data Source=YourServer;Initial Catalog=YourDatabase;
User Id=UserName;Password=Password;
With Windows Authentication, the Windows OS takes care of user management. All interaction with the database is done in the context of the calling user (more on that later) so the database knows who's accessing the system, without an explicit user name and password being passed in the connection string. You still need to map a Windows account to a SQL Server account so SQL Server can determine whether the account has sufficient permissions. I'll show you how to do this later.
A typical connection string using Windows Authentication can look like this:
Data Source=YourServer;Initial Catalog=YourDatabase;
Integrated Security=SSPI;
Instead of Integrated Security=SSPI you can also use Trusted_Connection=True which has the same effect.
In general, it's recommended to use Windows authentication. The fact that you don't need to use a password in the connection string, means your application will be a bit safer. You don't need to send the password over the wire, and there's no need to store it in a configuration file for your application where it can be viewed by anyone with access to that file.
However, SQL Server Authentication is a bit easier to use. Since you specify your own user name and password, you don't need to know the final user account that your application runs under.
Notice that it is possible in SQL Server to disable SQL Server Authentication (but not Windows Authentication). You can configure this setting through the server's Properties dialog in the Management Studio or Enterprise Manager. The following screen shot shows the settings dialog for SQL Server 2005:

Figure 1: The SQL Server 2005 Server Properties Dialog
You can see from this screen shot that this instance of SQL Server is configured to allow both authentication mechanisms.
Another area you need to know a bit more about is user accounts. When you use SQL Server Authentication, things are simple. The account used is the account you specify in the connection string. But when you have a connection to SQL Server with Windows Authentication, that connection runs under the credentials of a specific user account. What that account is, depends on the application and its configuration. The following FAQ explains how you can find out the user account when you are using Internet Information Services (IIS) as the web server: "How Do I Determine the Security Account that IIS Uses to Run My Web Site?". For most scenarios this FAQ will be enough; however, when you are running a web site from within Visual Studio 2005 using the built-in development web server Cassini, the actual account used by the web server process is your own account that you use to log on to your Windows machine. So, keep that in mind when you have a site in Visual Web Developer and run it against the development web server.
Now that you are familiar with the important terminology, it's time to look at a number of different scenarios. In the section that follows, I'll show you how to configure your application and SQL Server in 3 different scenarios. For these scenarios, I'll use a machine called Development that holds the web site and an installation of SQL Server called Development\Sql2005. In my examples, I am using a database called BugBase, taken from my latest book ASP.NET 2.0 Instant Results.
Before I show you the three different scenarios, let's take a look at attaching databases to your SQL Server installation. Unlike file based databases like Microsoft Access, a SQL Server database need to be attached to a running instance of SQL Server. Once you've attached the database, it remains attached until you either delete or detach it. This works a little bit different for databases that run under SQL Server Express. For more details about this, check out Working with User Instances on the MSDN site.

At this stage, by default only the administrative accounts (Windows administrators or the SQL Server SA account) have access to the database. With your database attached to your instance of SQL Server, it's time to look at configuring the database and the application.
From a configuration point of view, this is probably the easiest scenario to configure: all you need to do is create a user in SQL Server, assign a password and then use that account in the connection string. The first action in this process is to add a user account. To do this, follow these steps:
The final step is to give this new account the proper permissions to your database:



Pfew, a lot of work, right? Fortunately, most of the work is now done. The next step is testing it out. In the following section, I'll walk you through creating a simple web site that displays data from the BugBase database with the user accounted created and configured in the previous steps.
<connectionStrings>
<add name="BugBase"
connectionString="Data Source=.\SQL2005;
Initial Catalog=BugBase;
User ID=MyWebsiteUser;password=Pa$w0rD"
providerName="System.Data.SqlClient" />
</connectionStrings>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:BugBase %>"
SelectCommand="SELECT [Id], [Title] FROM [Bug]">
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="True" DataKeyNames="Id"
DataSourceID="SqlDataSource1">
</asp:GridView>
This is a common scenario, especially when you're developing your site on your local machine. Both the web server (either IIS or the built-in development web server) and SQL Server run on the same physical machine. This scenario makes it easy to use Integrated Security because both the web server and SQL Server can use the same Windows account. To configure your server for this scenario, follow these steps:


The next step is testing out these settings. In the following section, I'll walk you through creating a simple web site that displays data from the BugBase database with the user accounted created and configured in the previous steps. Notice that these steps are similar to those from scenario 1 earlier in this article. However, you'll need to use a different connection stirng, and configure IIS for your web site.
<connectionStrings>
<add name="BugBase"
connectionString="Data Source=.\SQL2005;Initial Catalog=BugBase;
Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:BugBase %>"
SelectCommand="SELECT [Id], [Title] FROM [Bug]">
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="True" DataKeyNames="Id"
DataSourceID="SqlDataSource1">
</asp:GridView>
This is another common scenario and one that you're likely to encounter in a production environment. The web site (or sites) run on a dedicated web server, while the data comes from a dedicated SQL Server machine. Quite often, the authentication mechanism in this scenario is SQL Server authentication. The reason behind this is that it's easy to set up. You don't need to be aware of what account is used by the web server, as you explicitly send a user name and a password in the connection string to the database. However, you don't have to use this security mechanism; it's quite possible to use Windows Authentication as well as long as the two machines are on the same network.
When using this scenario, there are two options that you need to be aware of: both machines fall under the same Windows domain, or both machines can be seen as independent, stand alone machines. In both configurations, the actions you need to perform are very similar to those of scenario 2. However, it's the exact user account that is different. The next two sections describe this in more detail.
When both machines are part of the same Windows Domain, you can configure IIS to run the web site under a specific domain account, like YourDomain\AnonIIS. For more details about configuring IIS, check out this FAQ: "How Do I Setup IIS to Allow it to Use Network Resources?" There's one caveat that you need to be aware of in ASP.NET pages: even if you specify a domain account in IIS, the ASP.NET web site will still run under MachineName\ASPNET or MachineName\Network Service.
However, you can change this behavior by modifying the Web.Config file for the application. To make the change, you can add an <identity impersonate="true" /> element to the <system.web> section. If you add the element, IIS will impersonate the current user and use that account instead of the ASPNET account. In this case, the "current user" means the account you set in the Anonymous access box when you're using anonymous access. Otherwise, the current user means an authenticated visitor.
When you have configured IIS to run under a domain account, and configured the application to use impersonation, the final step is to add the domain account as a user to SQL Server and your database. This works almost the same as described in scenario 2. The only difference is that the account you need to add follows the pattern of Domain\AccountName and not MachineName\AccountName.
Once again, this scenario is similar to scenario 2 in terms of configuring SQL Server. However, since both machines have different names, and thus different user accounts, it may seem impossible to add the account that is used by IIS on one machine to SQL Server on the other. The trick in this scenario is to use "mirrored accounts". You create accounts with identical names and passwords on both machines, for example MyWebsiteAccount. On the machine that runs IIS, you use this account in the Anonymous Access dialog for IIS and add an <identity impersonate="true" /> element to your application's configuration file. For more details, see the previous section "Sharing the Same Windows Domain". Then on the database server, you add the account MachineName\MyWebsiteAccount to SQL Server and your database. This works at run time, because the internal representation of the Windows account will be the same, regardless of the machine where the account was created.
For more information about mirroring the accounts, check out the section "Synchronize the IUSR Account" of this FAQ. Although the FAQ speaks about synchronizing the IUSR account in a classic ASP scenario, the same principles apply to ASP.NET.
When working with SQL Server 2005, you may also receive the following error: "An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections."
In a default installation, SQL Server only allows local applications to connect. To resolve this, and grant remote systems access to the database as well, follow these steps:
You'll need to restart SQL Server for the changes to take effect. You can do this under the SQL Server 2005 Services node in the same dialog, or through the Services panel of the Administrative Tools of Windows.
As you have seen, securing SQL Server and ASP.NET applications is a daunting task. In many situations, you're better off leaving this to your system or database administrator. However, if you don't have a security specialist, or you are the system or database administrator, this article hopefully has given you some valuable insight in securing SQL Server and your application.
Please note that since this security topic is so broad, I haven't been able to describe each and every scenario, step or concept in great detail. If you feel something important is missing, feel free to contact me, describe what you're missing and I'll update the article.
Source Code for this Article
This download contains a default ASP.NET page with a simple GridView and a SqlDataSource so you can test things out. It also contains a sample Web.Config file with two connection strings: one that uses SQL Server Authentication and one that uses Windows Authentication. Don't forget to update both the connection strings and the SELECT statement in the ASPX page when you use this sample. Also, since the Web.Config file contains two connection strings with the same name, you need to make sure that you comment out the one you don't need.
Wonder where to go next?
You can read existing comments below
or you can post a comment yourself on this article.
Consider making a donation
Please consider making a donation using PayPal. Your donation helps me to pay the bills so I can keep running Imar.Spaanjaars.Com, providing fresh content as often as possible.
I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.
When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.
If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the QuickDocId of the document.
For more information about the Talk Back feature, check out this news item.
| QuickDocId | 395 |
| Full URL | http://imar.spaanjaars.com/395/configuring-an-aspnet-20-application-to-work-with-microsoft-sql-server-2000-or-sql-server-2005 |
| Short cut | http://imar.spaanjaars.com/395/ |
| Written by | Imar Spaanjaars |
| Date Posted | 06/04/2006 00:12 |
| Listened to when writing | Take One (Re-built) by Front 242 (Track 16 from the album: Geography 2) |