Access an web service from web application with different default credentials
Today, a developer from the team asked me how to access a web service in our domain with user default credentials but for different user that those in WindowsIdentity.GetCurrent().
Let’s say that there is a web site that is configured to use Windows authentication in ISS and in the web configuration file we have Windows authentication with no impersonation. In addition, there is a web service that is configured in the same way. In such configuration HttpContext.User and Thread.CurrentPrincipal contain domain\user_name and WindowsIdentity is machine\aspnet. in such case when the web application tries to access the web service machine\aspnet user is used and such user doesn’t have rights to access the web service.
How to solve this?
The easiest way I have in mind is to impersonate the user from HttpContext.User. It is shown in the snippet below. This way the web service is called with right credentials.
1: CustomWebService.ServiceName service = new CustomWebService.ServiceName();
2: sws.Url = "<url>";
3: sws.UseDefaultCredentials = true;
4: CustomWebService.RetrievedData data;
5: using (WindowsImpersonationContext context = WindowsIdentity.Impersonate((HttpContext.Current.User.Identity as WindowsIdentity).Token))
6: {
7: data = service.GetSomeData();
8: }
9:
10: // use data retrieved from the service
Note that I use using statement in order to guarantee that after the scope I need impersonation it will be undone. i do not call directly Undo() method of WindowsImpersonationContext but it is called internally by Dispose() method.
Leave a Reply