Получить WindowsIdentity от ClaimsIdentity - PullRequest
0 голосов
/ 14 мая 2018

В моем ASP .NET MVC5 WebApp я использую идентификацию Овина для входа с учетными данными @ domain.com и получения данных с помощью Office 365 API Microsoft Graph.

Еще одна функция WebApp - чтение данных из Active Directory и предоставление пользователю возможности изменять их.

Я пытаюсь получить WindowsIdentity от текущего ClaimsIdentity, тип которого System.Security.Claims.ClaimsIdentity

Это функция сохранения:

public DateTime SaveWorker(WorkerAD worker, string mail = "")
{
    try
    {
        WindowsImpersonationContext impersonationContext = null;
        WindowsIdentity windowsIdentity = null;

        DirectoryEntry adsRoot = new DirectoryEntry(_directoryEntry);
        DirectoryEntry root = new DirectoryEntry(_directoryRootEntry);

        DirectoryEntry de = new DirectoryEntry();
        de.Path = "LDAP://" + root.Properties["dnsHostName"].Value + "/" + root.Properties["defaultNamingContext"].Value;

        de.AuthenticationType = System.DirectoryServices.AuthenticationTypes.Secure;
        DirectorySearcher searcher = new DirectorySearcher(adsRoot);
        if (String.IsNullOrEmpty(mail))
        {
            string user = HttpContext.Current.User.Identity.Name;
            searcher.Filter = $"(SAMAccountName={user.Replace("AD\\", "")})";
        }
        else
        {
            searcher.Filter = ("mail=" + mail);
        }
        SearchResult result = searcher.FindOne();

        windowsIdentity = HttpContext.Current.User.Identity.GetWindowsIdentity();
        impersonationContext = windowsIdentity.Impersonate();

        DirectoryEntry adUser = new DirectoryEntry(result.Path);

        adUser.AuthenticationType = System.DirectoryServices.AuthenticationTypes.Secure;

        adUser.Properties["telephoneNumber"].Value = worker.Telefon;
        adUser.Properties["mobile"].Value = worker.Mobile;
        adUser.Properties["facsimileTelephoneNumber"].Value = worker.Fax;
        adUser.Properties["title"].Value = worker.ADTitle;
        adUser.Properties["department"].Value = worker.Departement;

        adUser.CommitChanges();
        adUser.Close();

        return DateTime.Now;
    }
    catch (Exception)
    {

        throw;
    }
}

Где GetWindowsIdentity выглядит так:

public static WindowsIdentity GetWindowsIdentity(this IIdentity identity)
{
    WindowsIdentity windowsIdentity = null;
    string upnFromClaim = null;
    System.Security.Claims.ClaimsIdentity identity2 = (System.Security.Claims.ClaimsIdentity)identity;
    foreach (System.Security.Claims.Claim claim in identity2.Claims)
    {
        //if (StringComparer.Ordinal.Equals(System.IdentityModel.Claims.ClaimTypes.Upn, claim.ClaimType))
        if (claim.Type.Contains("preferred_username"))
        {
            upnFromClaim = claim.Value;
            break;
        }
    }
    windowsIdentity = S4UClient.UpnLogon(upnFromClaim);

    return windowsIdentity;
}

Я попытался адаптировать код, найденный здесь: Каков наилучший способ извлечь идентификатор WindowsIdentity из ClaimsIdentity , но он не работает.

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

System.Security.Claims.ClaimsIdentity Конечная точка не прослушивала в net.pipe: // localhost / s4u / 022694f3-9fbd-422b-b4b2-312e25dae2a2, который мог принять сообщение. Это часто вызвано неправильным адресом или действием SOAP. Смотрите InnerException, если имеется, для более подробной информации. enter image description here

Есть идеи, как этого добиться?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...