Mukarram Mukhtar

Web Security in .NET (p 2)

In part 1 of this article, I explained how to apply security on intranet web applications built in .NET (see details here). In this article, I’ll demonstrate how to apply security on internet web applications. The basic difference between the two starts when you set authentication mode in web.config. In intranet applications, we set authentication mode = windows, since we want our users to be authenticated on the basis of windows accounts; however, in case of internet web applications, we set authentication mode = forms. The reason behind this is, we authenticate users on the basis of their users accounts created by web forms of the application itself and have been saved in a database e.g. SQL Server or Oracle.

 

This might have given you a clear hint that in this example we’ll be dealing with a database, and for that purpose I choose my favorite one, SQL Server 2005 🙂

 

So before going into .NET IDE, let’s level the ground first, i.e. let’s create a database in SQL Server and create other tables and store procedures required to do all the authentication work.

 

Create & Get the Database Ready in SQL Server Management Studio:

Let’s open SQL Server Management Studio and right-click on the Databases folder and select New Database. Give database name STUDENT. After doing that I added a table, named STUDENT_INFO and added 3 fields in it i.e. ID, Name, Phone. I made ID a primary key and auto-number. Add a new user in SQL Server name student_dbo and assign STUDENT database as its default database. Furthermore, give student_dbo enough rights on the database to execute stored procedures, read/insert and delete records in tables. To keep things simple and straight, I’ve made student_dbo, dbowner of the database. After doing all the above steps, my database looks something like this:

 

 InternetCreateDatabase

  

How to Use aspnet_regsql.exe:

 

Now as you can see, there is only one table in the database and no stored procedure; but isn’t going to last for long. Now we’ll execute a utility called aspnet_regsql.exe that will add a whole bunch of new tables and stored procedures. Most of the times on web, you’ll find people telling you the command line to enter on command prompt; nonetheless, only a few people know that you can execute it just by double clicking on it and it will start a wizard for you. Locate aspnet_regsql.exe on your computer, depending upon your .NET version its location can be different e.g. for .NET 2.0 and 3.5 it’s location should be:

 

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

 

Now run the utility and go with the default settings in first few steps until you reach the step where you have to select a database. Now select the database that you just created, window should be like this:

 

 InternetRegSQL

 

Click Next, Next and Finish the wizard. After successfully completing the wizard, your database should look like this:

 

 InternetDatabaseReady

 

As you might have noticed quite a lot of new tables and stored procedures. Now let’s see how we are going to use these puppies.

 

Create .NET Web Application and Apply Security:

 

Let’s start,

 

  • Start Microsoft Visual Studio 2003 or later.
  • Click Create New Project
  • In New Project dialog box, select Visual C# in Project types panel on left.
  • Select ASP.NET Web Application in the Templates panel on right.
  • Give a decent physical path and name to your project and select OK.

 

 InternetNewProject

 

  • By doing this, IDE will create a web application project with a default form added into it.
  • Now add two folders in the root of the application named, Student and Admin; then add two web forms in each folder namely, StudentDefault.aspx and AdminDefault.aspx respectively.
  • In the root of the project, add a new form called Login.aspx
  • Open Login.aspx’s source in HTML view and set it’s form name to Login as follows:

 

<form id="Login" runat="server">

 

After performing above steps your project in the solution explorer should look something like this:

 

 InternetSolutionExplorer

 

After we have everything setup in solution explorer, now is the time we setup web.config. Enter the following connection string in web.config.

 

<connectionStrings>
      <remove name="Student_Connection"/>
      <add name="Student_Connection"
connectionString="Data Source=WIT-WS52;Initial Catalog=STUDENT;User Id=Student_dbo;pwd=student!@#;"
providerName="System.Data.SqlClient"/>
</connectionStrings>

 

It’s a simple connection string, no explanation needed for it. After this, we need to set authentication mode, membership provider and role manager of the application. In order to do that, we’ll add following lines in web.config (line numbers are given for understanding and are not part of actual code):

 

01 <authentication mode="Forms">
02    <forms name="Login" loginUrl="~/Login.aspx" protection="All" path="/" timeout="30"></forms>
</authentication>

 

03 <membership defaultProvider="AspNetSqlMembershipProvider">
<providers>
      <remove name="AspNetSqlMembershipProvider"/>
04    <add name="AspNetSqlMembershipProvider"
connectionStringName="Student_Connection"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/prjWebSecurityInternet"  
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""/>
      </providers>
</membership>

           

05 <roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">
<providers>
            <remove name="AspNetSqlRoleProvider"/>
06          <add name="AspNetSqlRoleProvider"
connectionStringName="Student_Connection"
type="System.Web.Security.SqlRoleProvider"/>
      </providers>
</roleManager>

 

In line 01 we are setting the authentication mode as “Forms”. Line 02 tells compiler the name of webpage and form which will authenticate users i.e. Login.aspx and Login respectively. Line 03 sets Membership provider; note connectionStringName=”Student_Connection” attribute, which tells compiler where to look for Membership and Roles related tables and stored procedures. Likewise, line 05 and 06 sets the role manager and again connection string attribute points to STUDENT database. Please carefully see all the attributes in these settings and apply and change according to your example application. After setting web.config, now we are ready to start coding in our application. Since this article is about showing how web security works in a website and how different users with different roles assigned to them are given/denied access on different folders with in the website; I won’t show how to code Create User Account web pages, simply because it is beyond the scope of our current topic. What I will show you is, however, how you can create roles and user accounts for this application without coding, rather, by using ASP.NET Configuration tool.

 

How to Use ASP.NET Configuration Tool:

 

Click on the ASP.NET Configuration button on the top right corner of Solution Explorer window in your IDE; this will open a new window as follows:

 

 InternetConfiguration1

 

Select Security link to quickly add two roles and two users for each role; I added two roles, role_Admin and role_Student as follows:

 

 InternetConfiguration2

 

I prefixed my roles with role_ so that role names Admin and Student do not conflict with any of the reserved words or database name. After adding roles I’m ready to add two users in each role. I added mack and frida as admin and student respectively as follows:

 

 InternetConfiguration3

 

Coding Authorization:

 

After adding the two users we are now ready to create the login screen and see how our application looks like without applying authorization. Remember, so far we’ve just applied authentication; applying authorization is still left. To understand the difference between the two, see part 1 of this article, here. To see authentication working, we’ll have to write a few very simple lines of code, let’s start with Login.aspx:

 

<body bgcolor="#cccccc">
    <form id="Login" runat="server">
    <div style="border-style:ridge; border-width:thin">
        <br />&nbsp; Welcome to Login Page:<br /><br />
        <asp:Login ID="Login1" runat="server" DestinationPageUrl="~/Default.aspx"
            DisplayRememberMe="False" TitleText="Please Log In" Width="300px">
        </asp:Login>
        <br />
    </div>
    </form>
</body>

 

All of the above lines are very simple HTML/ASPX code and I think no explantion needed even for novice .NET programmers. Now let’s move Default.aspx:

 

<body bgcolor="#cccccc">
    <form id="form1" runat="server">
    <div>
        Welcome <%= HttpContext.Current.User.Identity.Name %>!
        <br />
        This is Default Page.
        <br /><br />
        If you are a student, click
        <asp:HyperLink ID="hlStudent" NavigateUrl="~/Student/StudentDefault.aspx" runat="server">Students</asp:HyperLink>
        <br />
        Admins, click
        <asp:HyperLink ID="hlAdmin" NavigateUrl="~/Admin/AdminDefault.aspx" runat="server">Admins</asp:HyperLink>       
    </div>
    </form>
</body>

 

The only line which need explanation is <%= HttpContext.Current.User.Identity.Name %> which gets the name of the current authenticated user from the database. This line basically shows our web.config’s authentication mode related settings in action. StudentDefault.aspx and AdminDefault.aspx pages are almost ditto copy of each other and are as follows respectively.

 

<body bgcolor="#cccccc">
    <form id="form1" runat="server">
    <div>
        Welcome <%= HttpContext.Current.User.Identity.Name %>!
        <br /><br />
        This is Student Default Page. 
        <br /><br />
        <input type=button value="<- Back " onClick="history.back();"> 
    </div>
    </form>
</body>
 
<body bgcolor="#cccccc">
    <form id="form1" runat="server">
    <div>
        Welcome <%= HttpContext.Current.User.Identity.Name %>!
        <br /><br />
        This is Admin Default Page.  
        <br /><br />
        <input type=button value="<- Back " onClick="history.back();">
    </div>
    </form>
</body>

 

After adding the above lines in my web pages, when I ran the application, these pages looked like as follows:

 

 InternetLogin

 

After logging in, we’ll see Default page:

 

 InternetDefault

 

At this point, since we have not implemented authorization in web.config, no matter I select Admins or Students link, I’ll be redirected to the page I select. The two screen will show up as follows:

 

 InternetStudentDefault

 

 InternetAdmin

 

Now we’ve seen our application authenticating the user accessing it, let’s add authorization part of it. For this purpose, we’ll have to add following lines in web.config (again, line numbers are for understanding and not the part of actual code):

 

01    <location path="Login.aspx">
            <system.web>
                  <authorization>
02                      <allow users="*"/>
                  </authorization>
            </system.web>
      </location>
03    <location path="Default.aspx">
            <system.web>
                  <authorization>
04                      <allow roles="role_Student,role_Admin"/>
05                      <deny users="?"/>
                  </authorization>
            </system.web>
      </location>
06    <location path="Student">
            <system.web>
                  <authorization>
07                      <allow roles="role_Student"/>
08                      <deny roles="role_Admin"/>
09                      <deny users="?"/>
                  </authorization>
            </system.web>
      </location>
10    <location path="Admin">
            <system.web>
                  <authorization>
11                      <allow roles="role_Admin"/>
12                      <deny roles="role_Student"/>
13                      <deny users="?"/>
                  </authorization>
            </system.web>
      </location>

 

Line 01 starts with setting authorization of Login.aspx, line 02 sets it to allow access to all users. Line 03 tells that the coming block of Location node is for Default.aspx and line 04 tells us that users in role_Student  and role_Admin  are allowed to access this page. Line 05 tells that all anonymous users will be denied access on this page. Line 06 starts authorization settings on all pages in Student  folder, line 07 tells us that all users under role_Student  are allowed access on this folder; role_Admin  users and anonymous users have been denied access on this folder in lines 08 and 09 respectively. Similar to Student folder, we set authorization of Admin folder in lines 10, 11, 12 and 13.

 

After I added the above lines, when I login using frida’s user name/password I can’t access Admin Default page and likewise, when I login using mack’s user name/password and I try to access Student Default, I get redirected to Login page.

 

So dear readers, that’s all about applying security with authentication mode = forms i.e. authentication & authorization on internet web applications. Feel free to provide me with your feedback or ask for the source code. Make it a great day!

1 Comment »

  1. continuously i used to read smaller articles or reviews that also clear their motive, and that is
    also happening with this post which I am reading at
    this time.

    Comment by where can i buy wartrol — February 5, 2013 @ 2:56 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: