Microsoft OAuth 2.0 & Graph API using Python

Using http-requests, MSAL python library and FastAPI

Priyav K Kaneria
Workpeer
6 min readFeb 4, 2021

--

Introduction

Want to add 3rd party login to your web app? or you need the person’s Microsoft account details and make calendar events, drive folders and files using code?🤔
Welcome to the article!! Don’t waste your time and read this article fast (If you are a developer and stuck at some error😢, scroll down and understand the code you’ll get the solution 💻).

This tutorial assumes that you have basic understanding and knowledge of Python language.

In this tutorial, we are going to use FastAPI for the simple backend web app. If you are new to FastAPI I would recommend reading my previous article which covers fundamental basics of Building a web app using FastAPI.

We are going to build the backend for a simple Microsoft login application in this tutorial which will cover everything from logging in using Microsoft by getting access token, storing it in a cookie and using it to access user data (Strictly NOT for malicious purposes).

First Steps

So let’s get started! We will first take a look at what the application currently looks like. The code for this basic FastAPI application is available here (without the backend). You can clone the repo to work on the tutorial along with me.

Run the server and the web page should look something like this

uvicorn main:app --reload

Login Page for Microsoft SignIn

Please pip install the following requirements for the tutorial

pip install requests, msal

Understanding the Authorization flow

So let us first understand how the Microsoft OAuth 2.0 authorization flow works.

Authorization flow

What does this image mean😯? Let’s break it into parts.

STEPS TO GET ACCESS TOKEN -
1. Somehow go to an authentication URL that will show the sign in with Microsoft dialogue (we use MSAL library for the same).
2. User is asked to select account to sign in with.
3. User is asked to allow the App all requirements.
4. It takes us to a redirect-uri along with a code as query parameter.
5. We use MSAL library to get access_token from microsoft using the code which we get. (This skips the /oauth2/v2.0/token part for us)
6. We save the access token to a cookie.

Let’s start step by step

Making an Azure App

  1. First we will make an azure app.
  2. Go to this link and click on New Registration.
  3. Set any name of the app (this name will be shown to the users) and we will keep the app for accounts in any organizational directory.
  4. We have kept the redirect URI according to the API which we will make in our project.
Picture of the register app page
Application register page

Click on Register. Note down the client ID, it will be useful later.
Go to Certificates & secrets and create a new client secret.

Immediately save the client secret value and id somewhere as it is shown only once.

Now go to API permissions and add the permissions -
Under Microsoft Graph — openid and profile

You can add calendar and drive permissions if you are planning to get it’s access

Your Azure App is ready to be connected to our API’s🥳🥳

Building the Authentication URL

Now we use the MSAL library to build an Auth_url for us.
In main.py we do the following changes

main.py

NOTE: Make sure to replace my credentials with those I told you to save for later while creating credentials. The client ID is the one given in the overview tab in you Azure App.

Understanding the code

Now the time has come to understand the code line by line.

Let us start with main.py!. First of all, we import the msal library along with the required FastAPI functions. Then we declare global variables for all Microsoft credentials that will be required.

Next, we can see that we have defined a few functions that are well out of boundary for this article to cover and to be frank these have been defined by Microsoft themselves in their sample code (I have converted the sample from flask to FastAPI).

After that, we have the below code snippet:

Here we build an Authentication Url using the previously defined function and pass it to the template. In the template we simply use the SVG they provide for the sign in button and hyperlink it to the passed url.

Try running the server and check it out.

When we click on the button it should take us to a Microsoft page where we can login. After successful login a popup with something like this will come.

Allow app permissions Popup
Allow app permissions Popup

After you allow permissions and TADDAAA! You will be presented with an error😅 in the terminal, the template microsoft_proxy.html does not exist. And that’s exactly what we will do now. The html will serve as a temporary page to set the access token as a cookie and redirect us to homepage api.
Also, this is where we use the /add-microsoft-cookie API will be used (you thought I forgot that to explain, didn’t you?). Let me explain it to you below.

The microsoft_proxy.html is as follows -

microsoft_proxy.html

We use fetch API for making a post request to add-microsoft-cookie also passing the token as formdata, and in the API we have defined a response as a json response which contains all cookie data we need and returns it. If the cookie is returned successfully the fetch request makes the cookie and redirects us to the redirect_url which we pass as homepage.

If you run the server and try to login now, you can open the Application panel of the Developer console of you browser where you’ll find the localhost under the cookies. A cookie like Authorization Bearer eyB……*** will be present.

If you notice carefully we have successfully completed the Authentication process. The logout is simply deleting the cookie.
Still we need to also learn how to use those cookies, extract the token and use it to get user profile data.

Let us extract the cookie from the request and use it in the homepage API to get user basic data. For the same, we make the following changes to main.py-

Here we are using http-requests for getting user data according to the Microsoft Graph Documentation.
We use https://graph.microsoft.com/v1.0/me for getting the basic profile details.

I would suggest you to go here and check out all links to which you can make http-requests for either creating events in calendar, uploading files to drive, the documentation is all yours.

We need to make a little change to homepage.html for printing the details

And it’s done😎! We successfully got the user details.

Final Homepage UI

You can also go to http://localhost:8000/docs (while the server is running) and checkout the API’s we made in Swagger UI.
Stuck somewhere? Try loging in again after going to /logout. Still stuck? Raise an issue in the github repo.

So this is how to integrate 3rd party Microsoft Login to your web app using FastAPI and python.

You can get the repo here and comment below for any queries.

Thanks for reading, more on the way😇…

Also big thanks to Sebastián Ramírez for making FastAPI👌

--

--