Skip to content

Instantly share code, notes, and snippets.

@demelziraptor
Created February 16, 2014 19:34
Show Gist options
  • Save demelziraptor/9039435 to your computer and use it in GitHub Desktop.
Save demelziraptor/9039435 to your computer and use it in GitHub Desktop.
Code example to get a Sharepoint Access Token to use with the Sharepoint REST API using a python 3 provider-hosted Sharepoint App (using cherrypy). This code takes the data POSTed to it when you click on the app in Sharepoint, and authenticates using OAuth to get the access token. To use the Sharepoint REST API with OAuth, the app needs to be re…
import cherrypy
import jwt
import urllib.parse, urllib.request
import json
SPSECRET = 'gpYucHkODHOv6JxZJ89Kihl9ncTiTrUCAbOaF1N6uJE='
cherrypy.config.update({'server.socket_port': 3005,
'server.ssl_module': 'builtin',
'server.ssl_certificate': 'cert.pem',
'server.ssl_private_key': 'privkey.pem'})
class GetAccessToken(object):
def index(self, **kwargs):
cl = cherrypy.request.body.params
spapptoken = cl['SPAppToken']
decodedtoken = jwt.decode(spapptoken, SPSECRET, verify=False)
url = json.loads(decodedtoken['appctx'])['SecurityTokenServiceUri']
values = {
'grant_type': 'refresh_token',
'client_id': decodedtoken['aud'].split('/')[0],
'client_secret': SPSECRET,
'refresh_token': decodedtoken['refreshtoken'],
'resource': decodedtoken['appctxsender'].split('@')[0] + '/' + decodedtoken['aud'].split('/')[1].split('@')[0] + '@' + decodedtoken['appctxsender'].split('@')[1]
}
data = urllib.parse.urlencode(values)
binarydata = data.encode('ascii')
req = urllib.request.Request(url, binarydata)
response = urllib.request.urlopen(req)
page = response.read()
return repr(page)
index.exposed = True
cherrypy.quickstart(GetAccessToken())
@mauricionr
Copy link

Really thanks!

here is my solution for nodejs
https://gist.github.com/mauricionr/ce4c4af9eb845735a825

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment