Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Claims-based Authentication Example for interacting with Sharepoint Online
import os, requests, re
from htmlentitydefs import name2codepoint
from simplejson import loads, dumps
spauth = None
def unescape(s):
name2codepoint['#39'] = 39
return re.sub('&(%s);' % '|'.join(name2codepoint),
lambda m: unichr(name2codepoint[]), s)
def generate_saml(options):
# SAML.xml from
content = '<s:Envelope xmlns:s="" xmlns:a="" xmlns:u=""><s:Header><a:Action s:mustUnderstand="1"></a:Action><a:ReplyTo><a:Address></a:Address></a:ReplyTo><a:To s:mustUnderstand="1"></a:To><o:Security s:mustUnderstand="1" xmlns:o=""><o:UsernameToken><o:Username>[username]</o:Username><o:Password>[password]</o:Password></o:UsernameToken></o:Security></s:Header><s:Body><t:RequestSecurityToken xmlns:t=""><wsp:AppliesTo xmlns:wsp=""><a:EndpointReference><a:Address>[endpoint]</a:Address></a:EndpointReference></wsp:AppliesTo><t:KeyType></t:KeyType><t:RequestType></t:RequestType><t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType></t:RequestSecurityToken></s:Body></s:Envelope>'
for k in options.keys():
content = content.replace('['+k+']', options[k])
return content
def request_token(options):
saml = generate_saml(options)
result ='', data=saml)
return unescape(result.text.split('<wsse:BinarySecurityToken Id="Compact0">')[1].split('</wsse:BinarySecurityToken>')[0])
def get(url):
global spauth
return requests.get(url, headers={'Cookie':spauth, 'Accept':'application/json'})
opts = {
'username' : '',
'password' : 'password',
# First grab our token from
token = request_token(opts)
# Then use that token to authenticate on our site.
result =['endpoint'], token)
# For some reason, the requests module throws "s around each cookie, which messes up MSOnline's auth.
spauth = 'FedAuth=' + result.cookies['FedAuth'] + '; rtFa=' + result.cookies['rtFa']
# Lastly, let's test our authentication by grabbing some list data.
result = get('')
root = loads(result.text.encode('utf-8'))
import pprint
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.