22 April 2011

NTLM problem: The request failed with HTTP status 401: Unauthorized

I've written before in this blog about the problem of those who work with NTLM and not with Kerberos.

When you are try to get data from web-service that location in a remote server and you get the following message:
The request failed with HTTP status 401: Unauthorized

You are in the same problem like me.
At the time I offered a solution that wrap the connection by Thread

WSrv.MyService wsrv = new MyService();
System.Threading.Thread t = new System.Threading.Thread(delegate()
{
    resp = wsrv.CallMyWebService(prms);

});
t.Start();
t.Join();


This time I will offer another solution - impersonation
you need to wrap your the connection code to the web-service using impersonation

using (WindowsImpersonationContext impersonation = WindowsIdentity.Impersonate(IntPtr.Zero)) {
    WSrv.
MyService wsrv = new MyService();

    resp = wsrv.CallMyWebService(prms);
}


The advantage of the first approach - the user is saved, but it's not a good design pattern - any tread in .Net is 1MB (it's a lot of memory) – see example

The advantage of this second approach good pattern design - do not take resource so important as memory. Drawback that the user comes to web-service is the application pool

hope not complicated,
Roi