Using CLR Role-Based Security in Windows

Within the Common Language Runtime are classes that allow you to further programmatically determine which user account your code will execute under and allow things to happen outside of the rights assigned under a Windows account. In other words, it is possible to have users that are Windows users that have administrative rights within the application but are not actually in the Administrators group on Windows NT/2000/XP. The same is true of assemblies. They may have administrative logic built in, but not be part of the local administrators group.

The main reason for this starts with the principal. Basically, a principal is like a proxy that can act on behalf of a user, but also can assume the identity and role of that user. Within the .NET Framework, there are three basic principals:

  • Generic Principals— These are users that may or may not exist within a Windows 2000 domain and, therefore, may have privileges within an application that they may not otherwise have.

  • Windows Principals— These are Windows users within a role or group on Windows NT and/or Windows 2000. They can impersonate other users, meaning that they can access resources on behalf of another user while presenting that user's credentials.

  • Custom Principals— This group is defined by an application, and the rules are set by that application and/or its configuration.

Now, because principals are used to determine what is in a role or what a user can do, it makes demands to determine whether or not a request can be completed. A demand will succeed only if the user is allowed to perform the task requested; otherwise, a security exception is thrown. This process is managed by the PrincipalPermission class. The PrincipalPermission class is part of the System.Security namespace. Within this are numerous members that are quite fun to play with and very informative when it comes to managing and recording who does what with what context and when they did it. Listing 14.6 demonstrates creating a new PrincipalPermission and executing a demand. Note that this call could be made imperatively by calling the IPrincipal.IsInRole method as well.

Listing 14.6. Creating a PricipalPermission Code Snippet
try
{
String id = "Joe";
String role = "Sales";
PrincipalPermission PrincipalPerm1 = new PrincipalPermission(id, role);
PrincipalPerm1.Demand();
}
catch(SecurityException e)
{
... do something to handle the error
}

Figuring out who the Windows user is during this process can be done under one condition, the user must be authenticated by one of the methods listed at the beginning of this chapter. The following code sample in Listing 14.7 is a complete listing for the file named WebForm1.aspx.cs. This is the “code behind” file that Visual Studio.NET will compile to a DLL. I left everything completely generated as it appears in Visual Studio.NET to illustrate exactly what you may see when developing. The environment for this file to execute in is a Web with Anonymous Access turned off and only Windows Integrated Authentication turned on. This sample also shows how using the authentication mode of Windows allows ASP.NET to automatically wire the User object to your application. The complete sample is included on the book's Web site.

Listing 14.7. WebForm1.aspx.cs (Complete)
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace Chapter14
{
 /// <summary>
 /// Summary description for WebForm1.
 /// </summary>
 public class WebForm1 : System.Web.UI.Page
 {
  private void Page_Load(object sender, System.EventArgs e)
  {
   // Put user code to initialize the page here
   if(User.Identity.IsAuthenticated)
   {
    Response.Write("Authenticated as : " + User.Identity.Name);
   }
   else
   {
    Response.Write("You are not authenticated.");
   }
  }

  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: This call is required by the ASP.NET Web Form Designer.
   //
   InitializeComponent();
   base.OnInit(e);
  }

  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {
   this.Load += new System.EventHandler(this.Page_Load);
  }
  #endregion
 }
}

As stated before the sample, within IIS, Integrated Windows Authentication is the only option checked under Directory Security. Also, the web.config file is using the default setting of Windows for the authentication element's mode attribute. Listing 14.8 illustrates this.

Listing 14.8. web.config file (Complete)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <system.web>

    <!--  DYNAMIC DEBUG COMPILATION
          Set compilation debug="true" to enable ASPX debugging.  Otherwise, setting this
 value to
          false will improve runtime performance of this application.
          Set compilation debug="true" to insert debugging symbols (.pdb information)
          into the compiled page. Because this creates a larger file that executes
          more slowly, you should set this value to true only when debugging and to
          false at all other times. For more information, refer to the documentation about
          debugging ASP .NET files.
    -->
    <compilation
         defaultLanguage="c#"
         debug="true"
    />

    <!--  CUSTOM ERROR MESSAGES
          Set customError mode values to control the display of user-friendly
          error messages to users instead of error details (including a stack trace):

          "On" Always display custom (friendly) messages
          "Off" Always display detailed ASP.NET error information.
          "RemoteOnly" Display custom (friendly) messages only to users not running
          on the local Web server. This setting is recommended for security purposes, so
          that you do not display application detail information to remote clients.
    -->
    <customErrors
    mode="RemoteOnly"
    />

    <!--  AUTHENTICATION
          This section sets the authentication policies of the application. Possible modes
 are "Windows", "Forms",
          "Passport" and "None"
    -->
    <authentication mode="Windows" />

    <!--  APPLICATION-LEVEL TRACE LOGGING
          Application-level tracing enables trace log output for every page within an
 application.
          Set trace enabled="true" to enable application trace logging.  If
 pageOutput="true", the
          trace information will be displayed at the bottom of each page. Otherwise, you
 can view the
          application trace log by browsing the "trace.axd" page from your web application
          root.
    -->
    <trace
        enabled="false"
        requestLimit="10"
        pageOutput="false"
        traceMode="SortByTime"
  localOnly="true"
    />
    <!--  SESSION STATE SETTINGS
          By default ASP .NET uses cookies to identify which requests belong to a
 particular session.
          If cookies are not available, a session can be tracked by adding a session
 identifier to the URL.
          To disable cookies, set sessionState cookieless="true".
    -->
    <sessionState
            mode="InProc"
            stateConnectionString="tcpip=127.0.0.1:42424"
            sqlConnectionString="data source=127.0.0.1;user id=sa;password="
            cookieless="false"
            timeout="20"
    />

    <!--  GLOBALIZATION
          This section sets the globalization settings of the application.
    -->
    <globalization
            requestEncoding="utf-8"
            responseEncoding="utf-8"
   />

 </system.web>

</configuration>
					

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.225.173