I have an MVC3 webapplication which runs as a DOMAIN\USER1 account. This user has SPN in AD set and is trusted for delegation.
I want this application to access sharepoint server on behalf of the caller and upload the file for her/him. I use the following code
Dim request = HttpWebRequest.Create(http://sharepoint.domain.com)
request.Method = WebRequestMethods.Http.Head
request.PreAuthenticate = True
Dim identity = New WindowsIdentity(callerName & "#domain.com")
Dim impContext = identity.Impersonate()
'###### At this point identity.ImpersonationLevel is `Impersonate` not `Delegate`
request.Credentials = CredentialCache.DefaultNetworkCredentials
'###### DefaultNetworkCredentials is empty (Username, domain and password are all empty strings)
Dim response As HttpWebResponse
Try
response = request.GetResponse()
Return JsonSuccess()
Catch ex As WebException
'###### I get 401 Unauthorized exception
Return JsonError(ex.Message)
Finally
impContext.Undo()
End Try
My question is. Should the impersonation level at this point be Impersonate or Delegate (Sharepoint runs on a different machine than IIS server)?
In AD I also configured protocol transition for the sharepoint and HTTP, so maybe Impersonate should change to Delegate after it makes the request? I have no idea, guidance will be appreciated.
Another question is - shouldn't CredentialCache.DefaultNetworkCredentials contain at least the username of the impersonated user?
I found the answer here:
http://support.microsoft.com/kb/810572
"Kerberos does not work in a load-balanced architecture and IIS drops back to NTLM authentication. Because you cannot use NTLM for delegation, any applications or services that require delegation do not work. For more information, click the following article number to view the article in the Microsoft"
And that was exactly the case. I tried now with another machine that is not load-balanced and it works.
The only thing that still surprises me is that ImpersonationLevel of the identity is still Impersonate not Delegate...
Related
I am developing an intranet application (Windows Authentication) which download report stream from reporting server then save it as a file. When I ran it in debuging mode it works fine。 The code is as below:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.UseDefaultCredentials = true;
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream fStream = response.GetResponseStream();
However after I deployed it to the server, it won't get response rather than getting 401 unauthorized error.
Even I change the code to:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
string domain = ConfigurationManager.AppSettings["SchedulerDomain"];
string userName = ConfigurationManager.AppSettings["SchedulerUser"];
string passWord = ConfigurationManager.AppSettings["SchedulerPassword"];
NetworkCredential credential = new System.Net.NetworkCredential(userName, passWord, domain);
req.Credentials = credential;
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream fStream = response.GetResponseStream();
Get the same error. The user setup in the code has the permission to view/run the report.
The IIS7 is using Negotiate and NTLM. (Due to complicated reason, can't change Kerberos), run under ApplicationPoolIdentity
My question is, when I run it under debug mode, the user is my windows account, but why it fails when I tried to send the credential to the reporting server?
Anyone can help?
I capture all the request from the application server to the reporting server, find that all the requests' header's credential username and domain, password are null. Finally I think it is the NTLM causes the issue as here requires two credential hops which NTLM can't handle it, need use Kerberos.
There is another solution if you can't use Kerberos authentication: disable the asp.net impersonation, so from the app server to reporting server will use the applicationpoolidentity, which is a local machine account with account as such: domain/machinename$. So if you grant this account with browse permission on the reporting server, it should work.
I'm not sure how your IIS is configured but it seems like the Identity in your Application Pools setting for your app is overriding any supplied credential. Most obviously, the user that it is trying to authenticate with does not have access. That being said go to your IIS Manager and check the Identity settings for the site's Application Pool.
Change it to a user that has access to the report viewer and that should fix it. I've had a similar issue I posted here in case anyone is interested.
I have an MVC 4 application that allows a user to change their Active Directory password through a password reset functionality page. I have the following piece of code that sets the new password:
DirectoryEntry de = sr.GetDirectoryEntry();
de.Invoke("SetPassword", new object[] { newPassword });
de.Properties["LockOutTime"].Value = 0;
Upon trying to submit the form with the new password details I am having the following error written to the application event log:
0x80070005 (E_ACCESSDENIED))
I have set the Identity property of the Application Pool to NetworkService and had thought that this would have resolved the issue of connecting. Is there anything else further I need to ensure so that my ASPNET application can connect to the AD.
tl;dr
In our case, this started happening randomly. Turns out it's because our self-signed SSL certificate had expired. After creating a new one in IIS, the problem was resolved.
Explanation
This thread lead me to the cause.
I will briefly recap what SetPassword does here so you can see why you need it. That particular ADSI method really bundles 3 methods under the covers. It first tries to set the password over a secure SSL channel using LDAP. Next, it tries to set using Kerberos set password protocol. Finally, it uses NetUserSetInfo to attempt to set it.
The main problem is that only the first two methods will generally respect the credentials that you put on the DirectoryEntry. If you provide the proper credentials and an SSL channel for instance, the LDAP change password mechanism will work with those credentials...
If you check the NetUserSetInfo method, you will notice there is no place to put a username/password for authorization. In other words, it can only use the unmanaged thread's security context. This means that in order for it to work, it would have to impersonate the username/password combination you provided programmatically first...
LDAP over SSL is apparently the best way to go (and was the method that we had been using), and it appears (clarifications welcome) that once our self-signed SSL certificate had expired, it skipped Kerberos and fell back to NetUserSetInfo, which failed because it was not using the credentials we provided. (Or it just failed on Kerberos, as the poster said he had never seen the credentials passed in for Kerberos)
So after creating a new self-signed certificate (for COMPUTER.DOMAIN.local), the problem was resolved.
Here is the code (in case anyone's looking for it):
DirectoryEntry myDE = new DirectoryEntry(#"LDAP://OU=GroupName,DC=DOMAIN,DC=local");
myDE.Username = "administrator";
myDE.Password = "adminPassword";
DirectoryEntries myEntries = myDE.Children;
DirectoryEntry myDEUser = myEntries.Find("CN=UserName");
myDEUser.Invoke("SetPassword", new object[] { "NewPassword" });
myDEUser.Properties["LockOutTime"].Value = 0;
// the following 2 lines are free =)
myDEUser.Properties["userAccountControl"].Value = (int)myDEUser.Properties["userAccountControl"].Value | 0x10000; // don't expire password
myDEUser.Properties["userAccountControl"].Value = (int)myDEUser.Properties["userAccountControl"].Value & ~0x0002; // ensure account is enabled
myDEUser.CommitChanges();
i have some code that tries impersonate the callers windows security settings and then connect to another WCF service on a different machine
WindowsIdentity callerWindowsIdentity = ServiceSecurityContext.Current.WindowsIdentity;
using (callerWindowsIdentity.Impersonate())
{
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.Message;
binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
EndpointAddress endpoint = new EndpointAddress(new Uri("net.tcp://serverName:9990/TestService1"));
ChannelFactory<WCFTest.ConsoleHost.IService1> channel = new ChannelFactory<WCFTest.ConsoleHost.IService1>(binding, endpoint);
WCFTest.ConsoleHost.IService1 service = channel.CreateChannel();
return service.PrintMessage(msg);
}
But I get the error:
"the caller was not authenticated by the service"
System.ServiceModel .... The request for security token could not be satisfied because authentication failed ...
The credentials I am trying to impersonate are valide windows credential for the box the service is on.
Any ideas why?
In order to support your scenario, you need to have an understanding of how Protocol Transition and Constrained Delegation work. You will need to configure both Active Directory and your WCF service endpoint(s) to support this. Note the use of the Service Principal Name (SPN). Take a look at the following link and see if they help you. The article has a sample to demonstrate the complete end-to-end configuration required to make this work.
How To: Impersonate the Original Caller in WCF Calling from a Web Application
Agree with marc_s this is the double-hop problem.
You need to get the windows authentication all the way through, therefore:
The request must be made in the context of a windows users
IIS must be configured to use windows authentication
Web.config must be set up for windows authentication with impersonate = true
The user that your application pool is running as, must be allowed to impersonate a user. This is the usual place where the double-hop problem occurs.
There is a right called "Impersonate a client after authentication"
http://blogs.technet.com/askperf/archive/2007/10/16/wmi-troubleshooting-impersonation-rights.aspx
Impersonation from you service to the next is a tricky issue, known as "double-hop" issue.
I don't have a final answer for that (I typically avoid it by using an explicit service account for the service that needs to call another service).
BUT: you should definitely check out the WCF Security Guidance on CodePlex and search for "Impersonation" - there are quite a few articles there that explain all the ins and outs of impersonating an original caller and why it's tricky.
Marc
If you are sure you have the credentials right on both hops, the next thing that could be causing the issue is the lack of the EndpointDnsIdentity being set on the endpoint.
DnsEndpointIdentity identity = new DnsEndpointIdentity("localhost"); // localhost is default. Change if your service uses a different value in the service's config.
Uri uri = new Uri("net.tcp://serverName:9990/TestService1");
endpoint = new EndpointAddress(uri, identity, new AddressHeaderCollection());
My ASP.NET 2.0 app creates a HTTPWebRequest to a site within a company's intranet, which uses NTLM authentication. The credentials passed are for a service account, which is authenticated on the domain successfully (the security log confirms this)
Some abbreviated code follows..
HttpWebRequest req = WebRequest.Create(queryUrl) as HttpWebRequest;
NetworkCredential cred = new NetworkCredential(username,
pwd, domain);
req.Credentials = cred;
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
As part of the request, there are a couple of redirections (within the same domain) to the final response - which is handled OK on my dev machine (Windows 2k)
When this request is created from my deployment environment (Windows 2k3), I get a 401 Unauthorized error returned from the site, seemingly after the first redirect code is returned (301 Moved), and my request object attempts to follow the redirect.
So basically, does anyone know of any issues surrounding authenticated HttpWebRequests that follow redirections?
PS - The obvious workaround is to simply request the page redirected to - but I the admins in charge of the intranet site want to monitor my app's usage by redirecting me through a specific page.
For HttpWebRequest to reuse credentials across redirects you need to use a credential cache.
If you just assign a NetworkCredentials object it will only be used on the first request.
Here is an example:
HttpWebRequest req = WebRequest.Create(queryUrl) as HttpWebRequest;
NetworkCredential cred = new NetworkCredential(username, pwd, domain);
var cache = new CredentialCache {{queryUrl, "Ntlm", cred}};
req.Credentials = cache;
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
It's going to depend on how your auth. scheme works. The Network credentials is only going to help for the NTLM part of if. I suspect that the site you are trying to access is using forms authentication also. If this is the case, when you log in you should get an auth cookie, you will need to include that in subsequent requests, e.g. after a redirect. I think the WebRequest object has a headers collection that you can use to hold the cookie. Might be a good idea to use fiddler or firebug to see what is coming across when you normally browse.
If you are using NTLM, This is the classic 2 hop problem. It works on your dev machine because the client and the server are on the same box and the credentials are passed at most once (to the redirect final target machine i'm guessing)
When you deploy to your prod environment, there are 3 machines involved. Client browser passes credentials to server1, then server1 tries to pass the credentials to server2 which is not allowed. One work around is to implement Kerberos authentication (a stricter protocol) which will allow server1 to pass credentials to server2
When accessing my site, the user has to enter his credentials. They are basically plain directory access credentials.
At a certain point I check if a certain file they want to download exists by calling
WebRequest req = HttpWebRequest.Create(checkUri.AbsoluteUri);
WebResponse res = req.GetResponse();
Although I can access the checkUri from the browser, I get a 401 when doing the above check. I think I have to set the
req.Credentials
But I don't know where the current credentials are stored...
Any ideas?
--Update--
Integrated Windows Authentication: No
Allow Anonymous: Off
Caler: Link on page of same site (GET)
Impersonation: default is off (don't even know how to enable it in asp.net mvc)
I was having a similar problem on a site where I'm using forms authentication, I was able to solve this problem by using the code provided here as the second reply in the thread.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
// Add the current authentication cookie to the request
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
Cookie authenticationCookie = new Cookie(
FormsAuthentication.FormsCookieName,
cookie.Value,
cookie.Path,
HttpContext.Current.Request.Url.Authority);
req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(authenticationCookie);
WebResponse res = req.GetResponse();
I think you want this:
req.Credentials = CredentialCache.DefaultCredentials;
You're going to need to enable Integrated Windows Authentication.
I don't know what happens in ASP.NET MVC, but in ASP.NET Web Forms impersonation is turned on by:
<identity impersonate="true">
in web.config.