OAuth 2 Web 应用程序流的 Web 应用程序示例
Web 应用程序通常使用 OAuth。以下示例展示了使用 Flask Web 框架 和 GitHub 作为提供程序的此类 Web 应用程序可能是什么样子。它应该可以轻松地传输到任何 Web 框架。
注意
虽然大多数提供程序的流程保持不变,但 Github 的特殊之处在于 redirect_uri
参数是可选的。这意味着可能需要明确地将 redirect_uri 传递给 OAuth2Session
对象(例如,使用 flask-oauthlib
创建自定义 OAuthProvider 时)。
from requests_oauthlib import OAuth2Session
from flask import Flask, request, redirect, session, url_for
from flask.json import jsonify
import os
app = Flask(__name__)
# This information is obtained upon registration of a new GitHub OAuth
# application here: https://github.com/settings/applications/new
client_id = "<your client key>"
client_secret = "<your client secret>"
authorization_base_url = 'https://github.com/login/oauth/authorize'
token_url = 'https://github.com/login/oauth/access_token'
@app.route("/")
def demo():
"""Step 1: User Authorization.
Redirect the user/resource owner to the OAuth provider (i.e. Github)
using an URL with a few key OAuth parameters.
"""
github = OAuth2Session(client_id)
authorization_url, state = github.authorization_url(authorization_base_url)
# State is used to prevent CSRF, keep this for later.
session['oauth_state'] = state
return redirect(authorization_url)
# Step 2: User authorization, this happens on the provider.
@app.route("/callback", methods=["GET"])
def callback():
""" Step 3: Retrieving an access token.
The user has been redirected back from the provider to your registered
callback URL. With this redirection comes an authorization code included
in the redirect URL. We will use that to obtain an access token.
"""
github = OAuth2Session(client_id, state=session['oauth_state'])
token = github.fetch_token(token_url, client_secret=client_secret,
authorization_response=request.url)
# At this point you can fetch protected resources but lets save
# the token and show how this is done from a persisted token
# in /profile.
session['oauth_token'] = token
return redirect(url_for('.profile'))
@app.route("/profile", methods=["GET"])
def profile():
"""Fetching a protected resource using an OAuth 2 token.
"""
github = OAuth2Session(client_id, token=session['oauth_token'])
return jsonify(github.get('https://api.github.com/user').json())
if __name__ == "__main__":
# This allows us to use a plain HTTP callback
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = "1"
app.secret_key = os.urandom(24)
app.run(debug=True)
此示例是借鉴 此 gist 的。
注意:您应该注意,Oauth2 通过 SSL 层工作。如果您的服务器未参数化为允许 HTTPS,则 fetch_token 方法将引发 oauthlib.oauth2.rfc6749.errors.InsecureTransportError。大多数人在测试时不会在服务器上设置 SSL,这是正常的。您可以通过两种方式禁用此检查
通过设置环境变量。
export OAUTHLIB_INSECURE_TRANSPORT=1
2. 等同于上述内容,您可以在 Python 中设置此项(如果您在设置环境变量时遇到问题)
# Somewhere in webapp_example.py, before the app.run for example
import os
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'