Steve McLoughlin
Steve McLoughlin

Reputation: 75

Authorise with current user credentials for Python script accessing SharePoint list using NTLM

I have a script that checks a SharePoint list for a specific file revision and returns the result. This works well, but currently my authorisation method requires me to include my own password in the code to gain access to the SharePoint list, which isn't ideal given that passwords have to be updated frequently and other users can potentially view my login details.

Can someone point me in the right direction for using the current users credentials to access the SharePoint site? I've been going round in circles looking at ActiveDirectory, NTLM, SOAP etc and cannot decipher which of these is the most appropriate method.

I am using Python 2.7 and the working function is as follows:

import urllib2
from sharepoint import SharePointSite
from ntlm import HTTPNtlmAuthHandler

def read_sharepoint_list(current_project):
    # my Windows credentials
    username = "Domain\\user.name"
    password = "my_password"
    # the sharepoint info
    site_url = "http://SharePoint/"
    list_name = "My List"
    # an opener for the NTLM authentication
    passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
    passman.add_password(None, site_url, username, password)
    auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman)
    # create and install the opener
    opener = urllib2.build_opener(auth_NTLM)
    urllib2.install_opener(opener)
    # create a SharePointSite object
    site = SharePointSite(site_url, opener)
    sp_list = site.lists[list_name] 

    for row in sp_list.rows:
        if current_project in row.Filename:
            basecase_rev = row.Rev

    return basecase_rev

Upvotes: 7

Views: 19295

Answers (1)

Ryan D.W.
Ryan D.W.

Reputation: 373

There is an open pull request for the requests_ntlm library here to merge in SSPI authentication for Windows users. I had to make a few edits to the code for it to be functional, but it is working for me.

You'll first need to install requests and requests_ntlm, then modify the "requests_ntlm\__init__.py" package file (in your Python "Lib\site-packages" folder if on Windows) to resemble the following:

from .requests_ntlm import HttpNtlmAuth
from .requests_ntlmsspi import HttpNtlmSspiAuth

__all__ = ('HttpNtlmAuth', 'HttpNtlmSspiAuth')

Next, add the "requests_ntlmsspi.py" file (from the link above) to the "requests_ntlm" package folder.

You should then be able to authenticate using the current user's credentials as follows:

import requests
from requests_ntlm import HttpNtlmAuth, HttpNtlmSspiAuth

requests.get(site_url, auth=HttpNtlmSspiAuth())

Upvotes: 7

Related Questions