9

我正在使用WindowsTokenRoleProvider 来确定 ASP.NET Web 应用程序中的 Active Directory 组成员身份。

我的问题是性能不好,尤其是当用户在多个组中时。例如,我在 253(!) 个组中,并且WindowsTokenRoleProvider需要大约 150 秒来确定我在哪些组中。

我知道我可以使用缓存,这样就不会在用户的后续请求中执行此操作,但显然在第一次点击时花那么长时间是不可接受的。

我有哪些选择?我可以强制WindowsTokenRoleProvider只考虑某些群体吗?(我只对 5 个感兴趣)。

4

1 回答 1

13

一些测试表明我的问题是调用:

Roles.IsUserInRole(groupName)

正在访问 - 中的方法GetRolesForUser,该方法RoleProvider正在检索用户所属的每个角色的详细信息。

但是调用:

Roles.Provider.IsUserInRole(groupName)

确定用户是否在组中 - 无需检索用户所在角色的详细信息。

很奇怪,但看起来使用Roles.Provider.IsUserInRole会解决我的问题。

* 更新 *

事实证明,这只是部分解决方法;如果我在 web.comfig 中使用命令式权限检查或“允许”和“拒绝”,那么WindowsTokenRoleProvider仍然会继续并慢慢获取用户所属的每个组的详细信息:o(

所以我的问题仍然存在......

* 更新 *

我通过创建一个从 WindowsTokenRoleProvider 扩展并覆盖的类来解决这个问题,GetRolesForUser因此它只检查配置中指定的角色的成员资格。它也包括缓存:

/// <summary>
/// Retrieve the list of roles (Windows Groups) that a user is a member of
/// </summary>
/// <remarks>
/// Note that we are checking only against each system role because calling:
/// base.GetRolesForUser(username);
/// Is _very_ slow if the user is in a lot of AD groups
/// </remarks>
/// <param name="username">The user to check membership for</param>
/// <returns>String array containing the names of the roles the user is a member of</returns>
public override string[] GetRolesForUser(string username)
{
    // Will contain the list of roles that the user is a member of
    List<string> roles = null;

    // Create unique cache key for the user
    string key = String.Concat(username, ":", base.ApplicationName);

    // Get cache for current session
    Cache cache = HttpContext.Current.Cache;

    // Obtain cached roles for the user
    if (cache[key] != null)
    {
        roles = new List<string>(cache[key] as string[]);
    }

    // Was the list of roles for the user in the cache?
    if (roles == null)
    {
        roles = new List<string>();

        // For each system role, determine if the user is a member of that role
        foreach (SystemRoleElement role in WebConfigSection.Settings.SystemRoles)
        {
            if (base.IsUserInRole(username, role.Name))
            {
                roles.Add(role.Name);
            }
        }

        // Cache the roles for 1 hour
        cache.Insert(key, roles.ToArray(), null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);
    }

    // Return list of roles for the user
    return roles.ToArray();
}
于 2009-12-18T16:29:42.960 回答