Azure Python Flask External app consuming Office365 SharePoint Site


If you are not familiar with Flask, I highly recommend it for small projects with tight deadlines http://flask.pocoo.org/.


You can find the code in Github: https://github.com/pnp/PnP/tree/master/Samples/Python.Office365.AppAuthentication


Prerequisites before we go into the code:


  1. Office 365 developer tenant
  2. Visual Studio 2015 installed and Python Tools for Visual Studio installed or favorite IDE, or just a good text editor :).
  3. Python 2.7 or 3.4 installed
  4. Flask, requests, PyJWT Python packages installed via pip


Prepare the scenario for the Office 365 Python Flask app authentication sample


The Office 365 Python Flask application will:


  1. Use Azure AD authorization endpoints to perform authentication
  2. Use Office 365 SharePoint API's to show the authenticated user's title For these tasks to succeed you need to do additional setups explained below.
  3. Create Azure trial account with the Office 365 account so the app can be registered, or you can register it with PowerShell. A good tutorial can be found on this link https://github.com/OfficeDev/PnP/blob/497b0af411a75b5b6edf55e59e48c60f8b87c7b9/Samples/AzureAD.GroupMembership/readme.md.
  4. Register the app in the Azure portal and assign http://localhost:5555 to the Sign-on URL and Reply URL
  5. Generate a client secret
  6. Grant the following permission to the Python Flask app: Office 365 SharePoint Online > Delegated Permissions > Read user profiles
Azure portal
  1. Copy the client secret and the client id from the Azure portal and replace them into the Python Flask config file - Assign URL to the SharePoint site you are going to access to the RESOURCE config variable.


Visual Studio editor
  1. Open the sample in Visual Studio 2015 - Go to Project > Properties > Debug and dedicate 5555 for Port Number


Visual Studio Editor
  1. Go to Python environments > your active python environment > execute "Install from requirements.txt". This will ensure that all the required Python packages are installed.


Visual Studio Editor

Run the Office 365 Python Flask app sample


When you run the sample you'll see the title and login url.


Browser with an app

Once you've clicked the sign-in link, the Office 365 API will go through the authentication handshake and the Python Flask home screen will reload with the logged in user title and access token displayed:


Browser with an app