使用OAuth通过Django

时间:2017-07-24 20:58:49

标签: python django oauth microsoft-graph

我们正在创建一个在我们的组织中使用的应用程序,但我们只希望组织中的人员能够使用该应用程序。我们的想法是使用Microsoft的OAuth端点来验证用户是否属于我们的组织。我们的想法是在屏幕上显示一个登录屏幕,用户可以输入他们的Office 365用户名和密码,这样他们就可以在提交凭证时使用我们的应用程序。

我们的应用程序在Django上运行,我只使用Flask和Microsoft's Graph API connect sample for Python找到了解决此问题的方法(请参阅下面的代码段)。此示例使用与上面相似的想法登录到应用程序。 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 logins
    session['state'] = guid
    return 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 state
    if 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 access
    session['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'] = username
    session['userEmailAddress'] = email_address
    return redirect('main')

1 个答案:

答案 0 :(得分:0)

您应该能够使用几乎任何用于Python的OAUTH 2.0库。我没有使用Django,但我知道有几个用于Python。

我遇到了django-azure-ad-auth,这似乎正是您正在寻找的。

我还找到了一个名为django-allauth的通用OAUTH库,它似乎有很多活动。它没有内置的提供程序,但它们用于提供程序的模型看起来很简单,您可以毫不费力地扩展它。