0

我在构建一个在整个应用程序中使用的类时遇到了非常艰难的时期。问题与此处描述的问题完全相同: Sitecore switch user session with another user

在第一个用户之后登录的任何次要用户都共享一个会话变量。My Class 基本上为会话对象分配了一个权限级别,以便每个页面和/或控件都可以在不访问数据库的情况下读取它。

类结构如下:

Public NotInheritable Class cPermissions
    Public Shared Sub AssignPermissionToSession(ByVal UserID As Integer)
    Private Shared Sub SetInSession(key As String, value As Dictionary(Of String, String))
    Public Shared Function HasPerm(ByVal ControlName As String) as Boolean
End Class

所以解释一下这个过程:用户登录。登录代码调用cPermissions.AssignPermissionToSession(UserID)。该 Sub 调用 SetInSession 将权限字典分配给会话对象。

作为旁注,我更喜欢在此实例中使用 NotInheritable 类,因为它允许我使用共享函数 HasPerm 而不实例化该类来简化代码。HasPerm 读取会话对象,如果控件有权限,则返回 true 或 false。

所以回到原来的问题,根据前面一开始提到的链接,因为Sub是共享的,我遇到了session Hijacking。但是如果我不共享 SetInSession 子,则共享子 AssignPermissionsToSession(登录需要查看)无法访问它。

所以基本上,如果有人能指导我如何正确地构建这个类而不遇到意外会话劫持,我将非常感激。提前致谢!

要求的代码如下(为简洁起见):

Public NotInheritable Class cPermissions
    'local dictionary that gets created, and then assigned to session
    Private Shared dPermissions As New Dictionary(Of String, String)

    Public Shared Sub AssignPermissionToSession(ByVal UserID As Integer)
        dPermissions.Clear() 
        'Here I open DB and get a list of Roles that each member may have
        While ....
            BuildPermissionArray()
        End While

        'Now dPermission should be created assign to session
        SetInSession("Permissions", dPermissions)
    End Sub

    Private Shared Sub BuildPermissionArray()
         'Here we create the local Dictionary ready for the session
         'So for each role we get each permission for each control ie:
         dPermissions.add(control,perm)
    End Sub

    Private Shared Sub SetInSession(ByVal key As String, value As Dictionary(Of String, String))
        If value Is Nothing Then
            HttpContext.Current.Session(key) = New Dictionary(Of String, Integer)
        Else
            HttpContext.Current.Session(key) = value
        End If
    End Sub

    Public Shared Function HasPermission(ByVal PermissionType As Permission, ByVal ControlName As String) As Boolean
        Dim obj As Object = HttpContext.Current.Session("Permissions")
        Dim d As Dictionary(Of String, String) = DirectCast(obj, Dictionary(Of String, String))
        'Here I search the dictionary and check relevant permission for the control name
        Return result
    End Function
End Class                     

现在登录代码调用: cPermissions.AssignPermissionToSession(UserID)

并且每次页面加载都会读取当前页面上的控件并调用: cPermissions.HasPermission(View,"PageOrControlName")

4

0 回答 0