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')