首页 > 解决方案 > 查找用户如何跨域 c#

问题描述

UserPrincipal.FindByIdentity(...) 方法不能跨域工作。SingleSignOn 应用程序池正在运行的域之外的用户不会自动登录。当尝试以这些用户之一的身份访问 SingleSignOn 页面时,它会出现 NullReferenceException 错误


标签: c#.netactive-directorysingle-sign-onprincipalcontext

解决方案


如果您想要一种方法来检查各个域中的用户,则必须遍历各个域(用户有权读取每个域)。

如果您确实有用户可用的域信息,则可以将域作为参数添加到您的方法中。

我不确定是否AuthUserSession有任何可能包含用户域的属性。如果是这样,请使用它而不是传递给该方法的 domainName 参数。

public void LoadUserAuthInfo(AuthUserSession userSession, IAuthTokens tokens, Dictionary<string, string> authInfo, string domainName= someDefaultIfNoneProvided)
{
  if (userSession == null)
        return;
  string lookup = userSession.Id;
  List<string> domains = new List<string>() { "domain1", "domain2" };
  bool userFound = false;

  foreach (string domain in domains)  
  {
    using (var pc = new PrincipalContext(ContextType.Domain, domain))
    {
       var user = UserPrincipal.FindByIdentity(pc, userSession.UserAuthName);

       // ---> Add Check here to prevent NRE
       if (user != null) {
           SingleSignOnResponse ssoB = new SingleSignOnResponse();
           ssoB.Username = user.Sid.Translate(typeof(NTAccount)).ToString();
           ssoB.Timestamp = DateTime.Now;
           SSOCache.Instance.TryAdd(lookup, ssoB);
           userFound = true;
           break; // No longer need to continue checking other domains.
       }
       else 
       {
           // Handle case when user does not exist.
       } 
    }
  }
  // Check if userFound = false. If so, do something with that exception.
}

更新

如果您在 session.id 中有 domainName,请使用以下内容,

string lookup = userSession.Id;
  using (var pc = new PrincipalContext(ContextType.Domain, lookup.Split('\\')[0]))
  {
  ...

推荐阅读