Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
From the author of

From the author of

Implementing the XmlAuthorize Subroutine

The XmlAuthenticate subroutine is used to identify a user, and associate the user with a set of roles. The XmlAuthorize subroutine, on the other hand, is used to determine whether the current user is authorized to view a particular page.

The XmlAuthorize subroutine is contained in Listing 5.

Listing 5—XmlAuthorize Subroutine

Private Sub XmlAuthorize( s As Object, e As EventArgs )
 Dim application As HttpApplication 
 Dim arrAuthRoles As DataRow()
 Dim drowRole As DataRow
 Dim blnAuthorized = False

 application = CType( s, HttpApplication )
 arrAuthRoles = GetAuthRoles( application.Request.Path, application )
 For Each drowRole in arrAuthRoles
  If application.User.IsInRole( drowRole( "role" ) ) Then
   blnAuthorized = True
  End If
 Next
 If Not blnAuthorized Then
  application.Response.Write( "<h1>Forbidden!<h1>" )
  application.Response.End
 End If
End Sub

If the current user cannot be authorized to see the current page, then the message Forbidden! is displayed.

The XmlAuthorize subroutine calls the GetAuthRoles() function to return the list of roles that are authorized to view the current page. The GetAuthRoles() function is contained in Listing 6.

Listing 6—GetAuthRoles Function

Function GetAuthRoles( strUrl As String, application As HttpApplication ) As DataRow()
 Dim dstAuthRoles As DataSet
 Dim drowRoleList As DataRow()
 Dim drowRole As DataRow
 Dim colRoles As ArrayList
 Dim strFilePath As String

 dstAuthRoles = application.Context.Cache( "XmlAuthRoles" )
 If dstAuthRoles Is Nothing Then
  dstAuthRoles = New DataSet
  strFilePath = application.Server.MapPath( application.Request.ApplicationPath & "/XmlAuthRoles.xml" )
  dstAuthRoles.ReadXml( strFilePath )
  application.Context.Cache.Insert( "XmlAuthRoles", dstAuthRoles, New CacheDependency( strFilePath ) )
 End If
 Return dstAuthRoles.Tables( 0 ).Select( "path='" & strUrl & "'" ) 
End Function

The function in Listing 6 retrieves the contents of an XML file named XmlAuthRoles.xml (The XML file is cached for faster performance.) The XmlAuthRoles.xml associates one or more roles with pages in an application. A sample of an XmlAuthRoles.xml file is contained in Listing 7.

Listing 7—XmlAuthRoles.xml File

<pages>
 <url path="/myApp/private.aspx" 
  role="administrators" />
 <url path="/myApp/public.aspx" 
  role="guests" />
</pages>

According to the file in Listing 7, users in the administrators role can view the page located at the path /myApp/private.aspx, and users in the guests role can view the page located at /myApp/public.aspx.

  • + Share This
  • 🔖 Save To Your Account