Ошибка при использовании UserPrinciple на удаленном компьютере

Итак, у меня есть домен хостинга, в котором сейчас работает мое приложение на IIS 7, настройки пула приложений:

  • Идентичность: сетевая служба
  • Режим управляемого конвейера: интегрированный
  • Версия .NET: v4.0
  • Название: .NET v4.5

Параметры проверки подлинности IIS:

  • Анонимный: отключено
  • Выдача себя за другое лицо: включено
  • Формы: отключено
  • Windows: Включено

Также существует другая версия приложения, которая отлично работает с этими настройками. Итак, в моем текущем приложении у меня есть этот код для получения и сохранения SID пользователя:

public static SecurityIdentifier GenerateUserSID()
    {
        return (UserPrincipal.Current.Sid);
    }

public virtual ActionResult AddComment (string comment, int taskId, DateTime selectedDate)
    {
        var msg = string.Empty;

        try
        {
            Comment newComment = new Comment();

            var sid = ApplicationUtils.GenerateUserSID();

            newComment.CommentText = comment;
            newComment.Analyst = sid.ToString();
            newComment.TaskHistoryId = taskId;
            newComment.SelectedDateTimestamp = selectedDate;
            newComment.AddedTimestamp = DateTime.Now;

            _db.Comments.Add(newComment);
            _db.SaveChanges();
        }
        catch (Exception e)
        {
            msg = "Error: " + e;

            return Json(msg, JsonRequestBehavior.AllowGet);
        }

        return Json(comment, JsonRequestBehavior.AllowGet);
    }

И я получаю следующую ошибку:

System.DirectoryServices.DirectoryServicesCOMException (0x80072020): произошла ошибка операции. в System.DirectoryServices.DirectoryEntry.Bind (Boolean throwIfFail) в System.DirectoryServices.DirectoryEntry.Bind () в System.DirectoryServices.DirectoryEntry.get_AdsObject () в System.DirectoryServices.PropertyValueCollection.PopulateVervices .. ctor (запись DirectoryEntry, String propertyName) в System.DirectoryServices.PropertyCollection.get_Item (String propertyName) в System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer () в System.DirectoryDirectoryInitNoContainer () в System.DirectoryDirectoryInitNoContainer () в System.DirectoryDirectoryAccountManagementServices.AccountManagement.PackageServices. .PrincipalContext.Initialize () в System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx () в System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper (контекст PrincipalContext, Date PrincipalType, идентификатор System.DirectoryType, идентификатор System.DirectoryType) .AccountManagement.Princip al.FindByIdentityWithType (контекст PrincipalContext, тип PrincipalType, IdentityType identityType, String identityValue) в System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity (контекст PrincipalContext, IdentityType identityType, String identity.Value) в System. .Controllers.DashboardController.AddComment (строковый комментарий, Int32 taskId, DateTime selectedDate)

Это происходит только при доступе к приложению на удаленных машинах, на локальном все работает нормально.

Кто-нибудь знает, что вызывает это и как это исправить?


person GeorgeB    schedule 28.08.2018    source источник


Ответы (1)


Так что мне удалось это исправить, не меняя никаких разрешений в Active Directory.

Итак, теперь вместо ссылки на ApplicationUtils у меня есть это:

public virtual string GetSid()
    {
        using (HostingEnvironment.Impersonate())
        {

            PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

            UserPrincipal user = UserPrincipal.FindByIdentity(ctx, User.Identity.Name);

            var sid = user.Sid;

            return sid.ToString();
        }
    }

Итак, чтобы получить SID, мне просто нужно вызвать GetSid(), и он вернет строковую версию SID.

person GeorgeB    schedule 28.08.2018