Python 使用OAuth使用Django对Office 365/Graph用户进行身份验证
我们正在创建一个应用程序,供组织使用,但我们只希望组织中的人员能够使用该应用程序。我们想到了使用微软的OAuth端点来验证用户是否是我们组织的一部分。我们的想法是打开一个登录屏幕,用户可以在其中输入他们的Office 365用户名和密码,然后允许他们在提交凭据后使用我们的应用程序 我们的应用程序正在Django上运行,我只找到了使用Flask和的解决方案(请参阅下面的代码片段)。此示例使用与上面类似的方法登录应用程序。Django是否有类似的身份验证方法Python 使用OAuth使用Django对Office 365/Graph用户进行身份验证,python,django,oauth,microsoft-graph-api,Python,Django,Oauth,Microsoft Graph Api,我们正在创建一个应用程序,供组织使用,但我们只希望组织中的人员能够使用该应用程序。我们想到了使用微软的OAuth端点来验证用户是否是我们组织的一部分。我们的想法是打开一个登录屏幕,用户可以在其中输入他们的Office 365用户名和密码,然后允许他们在提交凭据后使用我们的应用程序 我们的应用程序正在Django上运行,我只找到了使用Flask和的解决方案(请参阅下面的代码片段)。此示例使用与上面类似的方法登录应用程序。Django是否有类似的身份验证方法 import requests from
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')
您应该能够使用任何用于Python的OAUTH 2.0库。我没有与Django合作过,但我知道Python有几种 我遇到了你想要的东西 我还发现了一个通用的OAUTH库,名为,它似乎有很多活动。它没有内置的提供程序,但是他们为提供程序使用的模型似乎足够简单,您可以轻松地扩展它