Using OAuth to authenticate Office 365/Graph users with Django

2024/10/14 4:23:23

We are creating an application for use in our organization, but we only want people in our organization to be able to use the app. We had the idea of using Microsoft's OAuth endpoint in order to authenticate whether a user is part of our org or not. The idea is to bring up a sign in screen where the user can enter their Office 365 username and password, which will then allow them to use our app upon submission of their credentials.

Our app is running on Django, and I've only found a solution to this problem using Flask and Microsoft's Graph API connect sample for Python (See code snippet below). This sample uses a similar idea to the one above to log in to the app. Are there any similar methods of authentication for Django?

import requests
from flask import Flask, redirect, url_for, session, request, render_template
from flask_oauthlib.client import OAuth# read private credentials from text file
client_id, client_secret, *_ = open('_PRIVATE.txt').read().split('\n')
if (client_id.startswith('*') and client_id.endswith('*')) or \(client_secret.startswith('*') and client_secret.endswith('*')):print('MISSING CONFIGURATION: the _PRIVATE.txt file needs to be edited ' + \'to add client ID and secret.')sys.exit(1)app = Flask(__name__)
app.debug = True
app.secret_key = 'development'
oauth = OAuth(app)# since this sample runs locally without HTTPS, disable InsecureRequestWarning
requests.packages.urllib3.disable_warnings()msgraphapi = oauth.remote_app( \'microsoft',consumer_key=client_id,consumer_secret=client_secret,request_token_params={'scope': 'User.Read Mail.Send'},base_url='https://graph.microsoft.com/v1.0/',request_token_url=None,access_token_method='POST',access_token_url='https://login.microsoftonline.com/common/oauth2/v2.0/token',authorize_url='https://login.microsoftonline.com/common/oauth2/v2.0/authorize')@app.route('/login')
def login():"""Handler for login route."""guid = uuid.uuid4() # guid used to only accept initiated loginssession['state'] = guidreturn msgraphapi.authorize(callback=url_for('authorized', _external=True), state=guid)@app.route('/login/authorized')
def authorized():"""Handler for login/authorized route."""response = msgraphapi.authorized_response()if response is None:return "Access Denied: Reason={0}\nError={1}".format( \request.args['error'], request.args['error_description'])# Check response for stateif str(session['state']) != str(request.args['state']):raise Exception('State has been messed with, end authentication')session['state'] = '' # reset session state to prevent re-use# Okay to store this in a local variable, encrypt if it's going to client# machine or database. Treat as a password.session['microsoft_token'] = (response['access_token'], '')# Store the token in another session variable for easy accesssession['access_token'] = response['access_token']me_response = msgraphapi.get('me')me_data = json.loads(json.dumps(me_response.data))username = me_data['displayName']email_address = me_data['userPrincipalName']session['alias'] = usernamesession['userEmailAddress'] = email_addressreturn redirect('main')
Answer

You should be able to use just about any OAUTH 2.0 library for Python. I've not worked with Django but I know there are several out there for Python.

I came across django-azure-ad-auth which seems to be exactly what you're looking for.

I also found a general OAUTH library called django-allauth which seems to have a lot of activity. It doesn't have a built-in provider but the model they use for providers seems simple enough that you may be able to extend it without too much trouble.

https://en.xdnf.cn/q/118000.html

Related Q&A

Python flatten array inside numpy array

I have a pretty stupid question, but for some reason, I just cant figure out what to do. I have a multi-dimensional numpy array, that should have the following shape:(345138, 30, 300)However, it actual…

Peewee and Flask : Database object has no attribute commit_select

Im trying to use Peewee with Flask, but I dont understand why my database connection does not work.config.pyclass Configuration(object): DATABASE = {name: test,engine: peewee.MySQLDatabase,user: root,p…

for loop to create a matrix in python

I am trying to study the probability of having a zero value in my data and I have developed a code that outputs the value of a column of data when the other is zero which is what I need. But having to …

How to convert List of JSON frames to JSON frame

I want to convert List of JSON object ot Single JSON frameHere is my codefor i in user1:name=i.namepassword=i.passwordid1=i.iduser = { "name" : name,"password" : password,"id&q…

Python 2.7 The packaging package is required; normally this is bundled with this package

I expect this has to do with the cryptography module, but Im not sure.Traceback (most recent call last):File "<string>", line 11, in <module>File "c:\python27\lib\site-packag…

Couple the data in all possible combinations

I have data in column in two columns like thisId Value 1 a 2 f 1 c 1 h 2 aand Id like couple the data of the Value column in all possible combinations based on the same Id such as(a,c) (a,h)…

Python - Find date from string

Would anyone know a regex string or another method of obtaining the date and time from this string into variables? The position of the string could change, so line and char no would not work. This is …

Get 1st column values on .csv file on python

i am newbie at python programming, i have a .csv file containing mac address and signal strength data from an AP consider my csv data is:i want to get just mac address values which is the 1st row, ref…

how to click mouse over sub menu in selenium?

I want to click invisible htmls sub menu click.*invisible html source<ul class="options"> <li class="_ranking-attr-filter-container _sub-menu-target"> <span>Hide w…

SSL: CERTIFICATE_VERIFY_FAILED certificate verify failed (_ssl.c.661)

Im trying to install nltk on my Mac, but I keep getting this error message after following these instructions: Install NLTK: sudo pip install -U nltk Install Numpy (optional): sudo pip install -U numpy…