Python urllib2 request exploiting Active Directory authentication
<p>I've got a Windows server (Navision) offering web access to its APIs through Active Directory authentication.<br/>
I'm trying to make a request to the web server through Active Directory authentication, by using an external Linux based host.</p>

<p>I successfully authenticated by using <code>python-ldap</code> library.</p>

<pre><code>import ldap
import urllib2

DOMAINHOST='domain_ip_host'

USERNAME='administrator@mydomain'
PASSWORD='mycleanpassword'

URL='http://...'

conn = ldap.open(DOMAINHOST)
ldap.set_option(ldap.OPT_REFERRALS, 0)

try:
    print conn.simple_bind_s(USERNAME, PASSWORD)
except ldap.INVALID_CREDENTIALS:
    user_error_msg('wrong password provided')
</code></pre>

<p>The output is in this case:</p>

<pre><code>(97, [], 1, [])
</code></pre>

<p>representing a successful authentication.</p>

<p>I'd need to exploit this successful authentication to communicate to the Navision web service, e.g. by using <code>urllib2</code> library.</p>

<pre><code>req = urllib2.Request(URL)
res = urllib2.urlopen(req)
</code></pre>

<p>Of course, since authentication is not exploited/adopted, the request fails with a <code>401 Unauthorized</code> error.</p>

<p>I also tried to use <code>python-ntlm</code> library:</p>

<pre><code>passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, URL, USERNAME, PASSWORD)
# create the NTLM authentication handler
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)

# other authentication handlers
auth_basic = urllib2.HTTPBasicAuthHandler(passman)
auth_digest = urllib2.HTTPDigestAuthHandler(passman)

# disable proxies (if you want to stay within the corporate network)
proxy_handler = urllib2.ProxyHandler({})

# create and install the opener
opener = urllib2.build_opener(proxy_handler, auth_NTLM, auth_digest, auth_basic)
urllib2.install_opener(opener)

# retrieve the result    
response = urllib2.urlopen(url)
print(response.read())
</code></pre>

<p>Also in this case, a <code>401 Unauthorized</code> error is provided.</p>

<p>How can I successfully make a web request by authenticating the user against Active Directory?</p>

<p>If it's a Dynamics NAV Webservice you want to trigger (didn't see that from code but from tag) you have to activcate ntlm on your NST.
Just change the Property 'ServicesUseNTLMAuthentication' from False to True in your CustomSettings.config or just use the Microsoft Dynamics NAV Administration MMC. Don't forget to restart the service after changing.</p>

python active-directory windows-authentication ntlm navision