In my ASP .NET MVC5 WebApp I am using Owin Identity to sign in with the @domain.com credentials and fetch data with the office 365 API Microsoft Graph.
Another functionality of the WebApp is to read data from the Active Directory and allow the user to modify it.
I am trying to get a WindowsIdentity from the current ClaimsIdentity, which type is System.Security.Claims.ClaimsIdentity
This is the save function:
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;
}
}
Where GetWindowsIdentity
looks like this:
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;
}
I have tried to adapt the code found here: What is the best way to retrieve a WindowsIdentity from a ClaimsIdentity but it is not working.
I get the following error:
System.Security.Claims.ClaimsIdentity There was no endpoint listening at net.pipe://localhost/s4u/022694f3-9fbd-422b-b4b2-312e25dae2a2 that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
Any idea how to achieve this?