Example: Securing an Intranet or Extranet Portal

 <  Day Day Up  >  

To illustrate the ideas outlines in this chapter, let's create a small demo portal site that demonstrates the following:

  • Authenticating users with Windows authentication turned on in all tiers on our system

  • Flowing user identity through the system layers

  • Authorizing users and protecting system resources based on the caller's role

  • Personalizing the portal based on caller identity and user profiles stored in the SQL Server database

Because it will be an intranet/extranet portal, we have good control over the user base and the environment. We can use Windows authentication in IIS, the ASP.NET application, and SQL Server. This option provides tight security and comes to us at no cost. With Windows authentication and impersonation turned on, code in all layers of our system executes under the caller identity, giving us constant access to identity information. Based on user identity and group membership, our system will grant or deny overall access and will give different access rights to our protected resources.

We are storing user profile information in a table in the SQL Server database. The key to this table is the username. The profile data is used by the ASP.NET application to customize the portal. Figure 6.13 illustrates this approach.

Figure 6.13. Portal Identity Flow

graphics/06fig13.gif


Let's outline our portal design goals:

  • Every user of your network can access the portal site except for members of the NoPortalForYou Windows group.

  • Our protected resource is the text file stored on the server. The file contains a memo from the management. Every authenticated user can read the file, which is displayed in a text box on the portal page. Members of the Managers Windows group can also modify contents of the text box and save it back to the memo file. We protect the file by configuring ACL for the file and hiding the Save command button if the caller does not belong to the Managers group.

  • SQL Server queries the tblUserProfile table based on the authenticated user's identity and returns two bits of information to the ASP.NET application: your preferred stock symbol and the background color you have selected for the page. ASP.NET personalizes the page by displaying the greeting with your name , showing the value of your preferred stock and painting the page background in the color of your choosing.

Now let's roll up our sleeves and start writing the code.

Step 1. Create Users and Groups

We start with creating three accounts for testing the application (Alice, Bob, and Mary) and two groups, NoPortalForYou and Managers . We also assign Mary to the NoPortalForYou group and Alice to the Managers group. To manage groups and users:

  1. Open Administrative Tools under Control Panel.

  2. Launch the Computer Management utility, and go to Local Users and Groups .

  3. Create these three users by selecting the New User option under Users (Figure 6.14).

    Figure 6.14. New User Dialog Box

    graphics/06fig14.gif


  4. Create two groups and set the groups' membership.

Figure 6.15 shows New Group dialog box where the group and its members' list are created.

Figure 6.15. New Group Dialog Box

graphics/06fig15.gif


Step 2. Create the SQL Server Profile Storage

The next step is to create our user profile storage in SQL Server:

  1. Open SQL Server Enterprise Manager and create a new SQL Server database called PortalDB with all default options.

  2. Right-click the Tables node under PortalDB and create a new table with three columns :

    • UserName ; key field containing user's login name

    • FavoriteStock to hold the user's stock symbol

    • BackgroundColor

  3. Save the table as tblUserProfile .

Figure 6.16 displays the SQL Enterprise Manager interface used to design and save a new table.

Figure 6.16. Create New Group

graphics/06fig16.gif


  1. Next open the table in Enterprise Manager and enter some test data as shown in Figure 6.17. Note that each UserName value contains the Domain Name prefix, which is likely to be different on your machine.

    Figure 6.17. Populate tblUserProfile

    graphics/06fig17.gif


  2. Create three SQL Server logins for Alice, Bob, and Mary specifying Windows as the authentication option and giving each new login a Public access to the PortalDB database (see Figure 6.11).

  3. None of the new SQL Server users has an access to tblProfileData table. To verify that, right-click the table, select Properties , and click Permissions (Figure 6.18). Because none of the check boxes is checked, even if the user is successfully authenticated and given database access, read/write on the table is prohibited .

    Figure 6.18. Default Permissions for tblUserProfile Prevent All Access

    graphics/06fig18.jpg


  4. To give authenticated users access to profile data, we create the view vwProfileData , which restricts table access to records owned by the user. Views are like predefined queries stored in SQL Server and are often used to customize or restrict data access. Create the view as shown in Listing 6.3.

    Listing 6.3. Create a View to Provide Access to Profile Data
     CREATE VIEW vwProfileData as SELECT * FROM tblUserProfile WHERE UserName = SYSTEM_USER 

    The SYSTEM_USER function resolves to the Windows Login name of the authenticated user; if Alice were to execute this view, she would be able to see only her profile data. Profile data of other users of the system is protected. This approach provides modularity and code reuse because other applications on your network might consume user profile data without having to worry about reimplementing security.

  5. Grant all users SELECT access to the view. Open the view's Properties dialog box, click Permissions , and check the SELECT box (Figure 6.19).

    Figure 6.19. Grant View Select Permission

    graphics/06fig19.jpg


Step 3. Create the ASP.NET Application

Finally we can create our portal application:

  1. Start Visual Studio .NET and create a new ASP.NET project called MiniPortal (Figure 6.20).

    Figure 6.20. Create an ASP.NET Project in Visual Studio

    graphics/06fig20.jpg


  2. As part of its magic, .NET creates a new IIS site for us. In IIS, open the Properties dialog box for the MiniPortal site, and click the Directory Security tab.

  3. Configure the site to use Windows authentication only (see Figure 6.3).

  4. Next we configure our ASP.NET application to use Windows authentication and impersonation. Locate and open the Web.config file in Solution Explorer in Visual Studio.

  5. Make sure that Windows authentication mode is selected and impersonation is on (see Figure 6.6).

  6. Visual Studio creates a default page for you. Rename it PortalPage.aspx and open it in design mode.

  7. Drop the following web controls on the default page:

    • Panel Panel1 to serve as a container for other controls

    • Label lblPortalName displaying the name of your portal site

    • Label lblGreeting , which holds personalized greetings

    • lblStock , which displays the value of your favorite stock

    • Text box txtMemo , which displays the contents of your protected resource ”the text file with the memo from management

    • Command button cmdSave , which allows members of the Managers group to save the memo

  8. Create a text file called C:\MEMO.TXT and write some fictitious memo to it.

  9. To configure ACL protection on this file, right-click it in Windows Explorer, select Properties , click the Security tab, and make sure that only the Managers group has Full Control access to the file.

  10. Return to Visual Studio and double-click the cmdSave command button to open the code-behind module of your page.

  11. Paste the code shown in Listing 6.4 there.

    Listing 6.4. Complete Code Listing for Portal Page
     ' Imports keyword allows us to add selected namespaces Imports System.Security.Principal Imports System.Threading Imports System.Data.SqlClient Public Class WebForm1  Inherits System.Web.UI.Page  Protected WithEvents txtMemo As System.Web.UI.WebControls.TextBox  Protected WithEvents lblStock As System.Web.UI.WebControls.Label  Protected WithEvents lblGreeting As System.Web.UI.WebControls.Label  Protected WithEvents cmdSave As System.Web.UI.WebControls.Button  Protected WithEvents lblPortalName As System.Web.UI.WebControls.Label  Protected WithEvents Panel1 As System.Web.UI.WebControls.Panel #Region "Web Form Designer Generated Code"  'This call is required by the Web Form Designer.  <System.Diagnostics.DebuggerStepThrough()> Private Sub _  InitializeComponent()  End Sub  Private Sub Page_Init(ByVal sender As System.Object, ByVal e As _  System.EventArgs) _  Handles MyBase.Init   'CODEGEN: This method call is required by the Web Form Designer   'Do not modify it using the code editor.   InitializeComponent()  End Sub #End Region   Private Sub Page_Load(ByVal sender As System.Object, ByVal e As _   System.EventArgs) _     Handles MyBase.Load   Try    '*** Here's our authorization and personalization rules:    '*** 1. Everyone except members of NoPortalForYou group can access _    the portal    '*** 2. Only members of Managers group can save memo text    '*** 3. Upon successful authentication, the portal site is _    personalized by    '***    - displaying your name    '***    - displaying the value of your favorite stock    '***    - paint the page background using your preferred color    '*** Since we have turned only Windows authentication on for IIS    '*** and Windows authentication and Impersonation for ASP.NET, only    '*** authenticated users can get here    '*** Determine the caller's identity:    If IsPostBack Then Exit Sub    Dim CurrentPrincipal As WindowsPrincipal = CType(context.User, _    WindowsPrincipal)    Dim strCallerIdentity As String = CurrentPrincipal.Identity.Name    '*** If the caller belongs to NoPortalForYou group, deny all access    If CurrentPrincipal.IsInRole("YOG\NoPortalForYou") Then     lblGreeting.Text = "System Access Denied"     lblStock.Visible = False     txtMemo.Visible = False     cmdSave.Visible = False     Exit Sub    End If    '*** If caller does not belong to Managers group, Save button _    should be hidden    If Not CurrentPrincipal.IsInRole("YOG\Managers") Then     txtMemo.ReadOnly = True     cmdSave.Visible = False    End If    '*** Now read user profile data from SQL Server table tblUserProfile    '*** since we configured SQL Server for Windows Authentication, we    '*** can use trusted connection which does not require explicit    '*** username or password    '*** Initial Catalog parameter of the connection string is the _    database name    '*** Data Source parameter of the connection string is the SQL _    Server name    Dim strConnectionString As String, strSQLQuery As String    strConnectionString = _    "Persist Security Info=True;trusted_connection=true;Initial _    Catalog=PortalDB;Data Source=."    strSQLQuery = "SELECT FavoriteStock, BackgroundColor FROM _    vwProfileData"    '*** connect to SQL Server    Dim DBConnection As New SqlConnection(strConnectionString)    DBConnection.Open()    '*** read user profile data    Dim Reader As SqlClient.SqlDataReader    Dim Command As New SqlCommand(strSQLQuery, DBConnection)    Reader = Command.ExecuteReader(CommandBehavior.SingleRow)    Dim strFavoriteStockSymbol As String = "", _        strBackgroundColor As String = ""    If Reader.Read() Then     strFavoriteStockSymbol = Reader.GetString(0)     strBackgroundColor = Reader.GetString(1)    End If    Reader.Close()    DBConnection.Close()    '*** Customize portal using profile data retrieved from database    If strFavoriteStockSymbol.Length > 0 Then _    ShowStockValue(strFavoriteStockSymbol)    If strBackgroundColor.Length > 0 Then     Dim MyColorConverter As New System.Drawing.ColorConverter()     Panel1.BackColor = MyColorConverter.ConvertFromString(strBackgroundColor)    End If    lblGreeting.Text = "Welcome " & strCallerIdentity    '*** Read memo from text file on the server    Dim FileReader As System.IO.StreamReader = _    System.IO.File.OpenText("C:\MEMO.TXT")    txtMemo.Text = FileReader.ReadToEnd()    FileReader.Close()   Catch ex As Exception    ' if error occurs put error description in the memo box and _    disable Save button    txtMemo.Text = ex.Message    cmdSave.Visible = False   End Try   End Sub   Private Sub ShowStockValue(ByVal strFavoriteStockSymbol As String)     If strFavoriteStockSymbol.Length = 0 Then       lblStock.Text = ""     Else       '*** In a real portal Web Service would get life stock value       '*** In this sample we generate it randomly (which by the way       '*** reflects my opinion of stock markets)       Randomize()       lblStock.Text = strFavoriteStockSymbol & _           " is at " & CInt(Int((100 * Rnd()) + 1)) ' random value _           between 1 and 100     End If   End Sub   Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As _   System.EventArgs) _   Handles cmdSave.Click     Try       '*** save the contents of the text box back to the memo file       Dim FileWriter As New System.IO.StreamWriter _       (System.IO.File.OpenWrite("C:\MEMO.TXT"))       FileWriter.Write(txtMemo.Text)       FileWriter.Close()     Catch     End Try   End Sub End Class 

    In the Load event of our page, we:

    • Make sure that members of the NoPortalForYou group cannot use the portal.

    • Hide the Save button and make the text box read only if the caller is not in Managers .

    • Use SQLDataReader to query the SQL Server database PortalDB .

    • Display the value of your stock, display your name, and paint the background in your preferred color.

    • Use the StreamReader object to read contents of the C:\MEMO.TXT file and display it in the txtMemo text box.

    The Click event of the cmdSave command button is available only to members of the Managers group. There we use the StreamWriter object to save the memo from the text box back to the file.

  12. Compile the application and test it logging out and logging in as Alice, Bob, and Mary. Using Mary's login, you cannot see portal data. When logging in as Alice, you have full access and can modify the memo. Logging in as Bob (shown in Figure 6.21), you still can use the personalized portal, but you can only read the memo.

    Figure 6.21. Portal Page for Bob

    graphics/06fig21.jpg


Be aware of a bug fixed in .NET Framework Service Pack 2: If you are a member of too many groups, the IsInRole function may fail and return false every time incorrectly. The bug, which has been confirmed by Microsoft, happens due to incorrect buffer allocation when you create a group list. If you log in as an administrator, you will belong to all groups and have a good chance of encountering this bug.

 <  Day Day Up  >  


Building Portals, Intranets, and Corporate Web Sites Using Microsoft Servers
Building Portals, Intranets, and Corporate Web Sites Using Microsoft Servers
ISBN: 0321159632
EAN: 2147483647
Year: 2004
Pages: 164

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net