Saturday, February 14, 2009

How to use AzMan to manage roles with Active Directory

How to use AzMan to manage roles with Active Directory

In my recent project I had a requirement to configure user roles in AzMan with Active Direcrtory. AzMan consist of Operations, Tasks and Roles.  List of operations can be added into Tasks and list of Tasks can be added into Roles.  You can play with AzMan with a snapin (just type Azman.msc in your run command) that will come with windows server 2003, or if you install 2003 administrative tools for XP professional.  

Sample Active Directory Connection String : 
msldap://Server IP/CN=AzManStore,DC=Domain Name

Initializing the AzMan Store:
Dim _AzManStore As New AzAuthorizationStore()
        _AzManStore.Initialize(0, Convert.ToString(ConfigurationManager.ConnectionStrings("ADRoleConnectionString")), Nothing)
        _azApp = _AzManStore.OpenApplication(Roles.ApplicationName)
        _azRoleProvider = New AzManRoleProvider()

Getting the list of Operations from AzMan:
Public Function GetOperations(ByVal username As String) As List(Of IAzOperation)
        Dim _Operations As New List(Of IAzOperation)

        For Each azOperation As IAzOperation In _azApp.Operations
            If Me.IsOperationAllowed(azOperation, username) Then
                _Operations.Add(azOperation)
            End If
        Next

        Return _Operations
    End Function

Getting the list of operations based on a given task:
Public Function GetOperationsByTask(ByVal username As String, ByVal taskName As String) As List(Of IAzOperation)
        Dim _Operations As New List(Of IAzOperation)
        Dim _azTask As IAzTask

        If taskName.Length > 0 Then
            _azTask = _azApp.OpenTask(taskName)

            For i As Integer = 0 To _azTask.Operations.Length - 1
                Dim _TaskOperation As IAzOperation = _azApp.OpenOperation(_azTask.Operations(i))
                If Me.IsOperationAllowed(_TaskOperation, username) Then
                    _Operations.Add(_TaskOperation)
                End If
            Next
        End If
        

        Return _Operations
    End Function

Checking whether an operation is allowed for a user:
Private Function IsOperationAllowed(ByVal pOperation As IAzOperation, ByVal pUsername As String) As Boolean
        Dim _User As MembershipUser = Membership.GetUser(pUsername)
        Dim userContext As IAzClientContext = _azApp.InitializeClientContextFromStringSid(_User.ProviderUserKey.ToString, 1, Nothing)

        'Check if user has access to the operations
        Dim operationIds() As Object = {pOperation.OperationID}
        Dim scope() As Object = {String.Empty}

        Dim result() As Object = userContext.AccessCheck("Auditstring", scope, operationIds)

        'Test the integer array we got back to see which operations are authorized
        If (result(0) = NO_ERROR) Then
            Return True
        Else
            Return False
        End If
    End Function 

No comments: