Skip to content

Instantly share code, notes, and snippets.

@tomkcook
Created March 20, 2018 15:50
Show Gist options
  • Save tomkcook/036706aa14a9194ef5e575c83402a7eb to your computer and use it in GitHub Desktop.
Save tomkcook/036706aa14a9194ef5e575c83402a7eb to your computer and use it in GitHub Desktop.
Authenticate against Sharepoint using flask-oauthlib (not yet working - see comments)
# Notes
# - All IDs are GUIDs
# - You get the client ID and the client secret by registering your app. You can
# do this through sharepoint online or through Azure AD.
# - Getting an access token goes in two steps; you request an authorization token from Sharepoint,
# then an access token from ACS.
# - Getting the authorization token from Sharepoint works (returned as a request to
# /login?code=XXX )
# - Getting the access token doesn't work. Apparently because Sharepoint and ACS disagree about
# what is a valid client ID. Sharepoint wants just the app's GUID, while ACS wants to see
# app_id@tenant_realm_id.
from flask import Flask, request, session
from . import settings
app = Flask(__name__)
app.config.from_object(settings) # for SECRET_KEY
from flask_oauthlib.client import OAuth
oauth = OAuth(app)
sharepoint = oauth.remote_app(
'sharepoint',
consumer_key = '<your sharepoint client ID>',
consumer_secret = '<your sharepoint secret>',
request_token_params = {'scope': 'AllSites.Manage'},
base_url = 'https://<yourcompany>.sharepoint.com/sites/<yoursite>/_layouts/15/OAuthAuthorize.aspx',
request_token_url = None,
access_token_method = 'POST',
access_token_url = 'https://accounts.accesscontrol.windows.net/tokens/OAuth/2',
access_token_params = {'resource': '<your tenant realm ID>'}
)
@sharepoint.tokengetter
def get_sharepoint_token(token=None):
return session.get('sharepoint_token')
@app.route('/')
def index():
return sharepoint.authorize(callback='https://{}/login'.format(settings.SERVER_NAME))
@app.route('/login')
def login():
resp = sharepoint.authorized_response()
if resp is None:
return 'Login failed: ' + request.args.get('error_description')
session['sharepoint_token'] = (
resp['oauth_token'],
resp['oauth_token_secret']
)
session['sharepoint_user'] = resp['screen_name']
return 'Hello, ' + resp['screen_name']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment