python - flask-oauthlib 服务器不能很好地与 requests-oauthlib 客户端配合使用

标签 python oauth flask oauth-2.0

我有一个启动并运行的 flask-oauthlib 服务器,当我使用来自 the example 的客户端代码时,我已经能够正确授权/验证.我意识到并非我所有的客户都会安装 flask-oauthlib,所以我尝试使用 requests-oauthlib 创建一个客户端,但它在我的服务器上失败了(即使 requests-oauthlib 提供的“Github 示例”工作正常) .

这是我的 requests-oauthlib 客户端代码:

from requests_oauthlib import OAuth2Session
from flask import Flask, request, redirect, session, url_for
from flask.json import jsonify
import os

app = Flask(__name__)

client_id = 'M2GCECELADgqZNke50iShcXRjq0pyO8i72W38l7U'
client_secret = 'ao5wrWp7RrUuKlgTxjmK6D7Z9dsPlI6fZc2WwkTTG4eEvXsN1q'
authorization_base_url = 'http://127.0.0.1:5000/oauth/authorize'
token_url = 'http://127.0.0.1:5000/oauth/token'

@app.route("/")
def demo():
  remote = OAuth2Session(client_id)
  authorization_url, state = remote.authorization_url(authorization_base_url)
  session['oauth_state'] = state
  return redirect(authorization_url)

@app.route("/authorized", methods=["GET"])
def authorized(): # this is where it fails
  remote = OAuth2Session(client_id, state=session['oauth_state'])
  token = remote.fetch_token(token_url, client_secret=client_secret, authorization_response=request.url)
  session['oauth_token'] = token
  return redirect(url_for('.profile'))

@app.route("/profile", methods=["GET"])
def profile():
  remote = OAuth2Session(client_id, token=session['oauth_token'])
  return jsonify(remote.get('http://127.0.0.1:5000/api/me').json())

if __name__ == "__main__":
  os.environ['DEBUG'] = '1'
  app.secret_key = os.urandom(24)
  app.run(host='localhost', port=8000,debug=True, use_reloader=False)

在服务器上,这是 token_handler。它目前返回无,我试图让它返回一个字典和一个 json 编码的字典,但没有成功。

@app.route('/oauth/token')
@oauth.token_handler
def access_token():
  return None

我的其余服务器代码直接取自 the flask-oauthlib example

为什么这适用于一个 oauthlib 客户端而不适用于另一个?我是 oauthlib 的新手,所以也许我错过了一些简单的愚蠢的东西?

编辑:我正在使用:

oauthlib 0.6.1
flask-oauthlib 0.4.3
requests 2.2.1
requests-oauthlib 0.4.0
flask 0.10.1
python 2.7

编辑 #2:request-oauthlib 客户端的日志记录:

Requesting url http://127.0.0.1:5000/oauth/token using method POST.
Supplying headers {u'Accept': u'application/json'} and data {u'code': u'vG7shZebClhAjzmSUQuHoqlXNrPTVr', u'client_secret': u'qdlmQvf5tdSVxFqixeE4wOKxe3awfEbsymCOpjeTIZEaWjbbB5', u'grant_type': u'authorization_code', u'client_id': u'EXewK3X3dU1NiWk7AfNj43jrhpSy8bHQm1mOHC96'}
Passing through key word arguments {'auth': None}.
Prepared fetch token request body grant_type=authorization_code&code=vG7shZebClhAjzmSUQuHoqlXNrPTVr&client_id=EXewK3X3dU1NiWk7AfNj43jrhpSy8bHQm1mOHC96&client_secret=qdlmQvf5tdSVxFqixeE4wOKxe3awfEbsymCOpjeTIZEaWjbbB5
Request to fetch token completed with status 405.
Response headers were CaseInsensitiveDict({'date': 'Tue, 25 Feb 2014 21:19:32 GMT', 'content-length': '178', 'content-type': 'text/html', 'allow': 'HEAD, OPTIONS, GET', 'server': 'Werkzeug/0.9.4 Python/2.7.5+'}) and content <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>
.
Invoking 0 token response hooks.
127.0.0.1 - - [25/Feb/2014 14:19:32] "GET /authorized?state=qPJnIJctmsTbojT2nTOkgRNwgnU8vF&code=vG7shZebClhAjzmSUQuHoqlXNrPTVr HTTP/1.1" 500 -
Traceback (most recent call last):
....
....
ValueError: No JSON object could be decoded

编辑 #3:服务器的 flask-oauthlib 日志记录:

Found redirect_uri None.
Validate client u'EXewK3X3dU1NiWk7AfNj43jrhpSy8bHQm1mOHC96'
Found default redirect uri 'http://localhost:8000/authorized'
Found default scopes ['email']
127.0.0.1 - - [25/Feb/2014 14:19:30] "GET /oauth/authorize?response_type=code&client_id=EXewK3X3dU1NiWk7AfNj43jrhpSy8bHQm1mOHC96&state=qPJnIJctmsTbojT2nTOkgRNwgnU8vF HTTP/1.1" 200 -
Fetched credentials from request {'state': u'qPJnIJctmsTbojT2nTOkgRNwgnU8vF', 'redirect_uri': None, 'response_type': u'code', 'client_id': u'EXewK3X3dU1NiWk7AfNj43jrhpSy8bHQm1mOHC96'}.
Found redirect_uri None.
Validate client u'EXewK3X3dU1NiWk7AfNj43jrhpSy8bHQm1mOHC96'
Found default redirect uri 'http://localhost:8000/authorized'
Persist authorization code {u'state': u'qPJnIJctmsTbojT2nTOkgRNwgnU8vF', u'code': u'vG7shZebClhAjzmSUQuHoqlXNrPTVr'} for client u'EXewK3X3dU1NiWk7AfNj43jrhpSy8bHQm1mOHC96'
Authorization successful.
127.0.0.1 - - [25/Feb/2014 14:19:32] "POST /oauth/authorize HTTP/1.1" 302 -
127.0.0.1 - - [25/Feb/2014 14:19:32] "POST /oauth/token HTTP/1.1" 405 -

编辑 #4:服务器的 oauthlib 日志记录:

Validating redirection uri None for client EXewK3X3dU1NiWk7AfNj43jrhpSy8bHQm1mOHC96.
Using default redirect_uri http://localhost:8000/authorized.
Validating access to scopes ['email'] for client u'EXewK3X3dU1NiWk7AfNj43jrhpSy8bHQm1mOHC96' (<api.models.Client object at 0x7fb104026e50>).
127.0.0.1 - - [25/Feb/2014 14:12:30] "GET /oauth/authorize?response_type=code&client_id=EXewK3X3dU1NiWk7AfNj43jrhpSy8bHQm1mOHC96&state=oHvelCpzosGfJd7ZzCeBvsmRANmipb HTTP/1.1" 200 -
Dispatching response_type code request to <oauthlib.oauth2.rfc6749.grant_types.authorization_code.AuthorizationCodeGrant object at 0x2db44d0>.
Validating redirection uri None for client EXewK3X3dU1NiWk7AfNj43jrhpSy8bHQm1mOHC96.
Using default redirect_uri http://localhost:8000/authorized.
Validating access to scopes [u'email'] for client u'EXewK3X3dU1NiWk7AfNj43jrhpSy8bHQm1mOHC96' (<api.models.Client object at 0x7fb10403e210>).
Pre resource owner authorization validation ok for <oauthlib.common.Request object at 0x7fb104026210>.
Created authorization code grant {u'state': u'oHvelCpzosGfJd7ZzCeBvsmRANmipb', u'code': u'yAZZwtCd1IyAeBtHEgg4YTnHl46Ddf'} for request <oauthlib.common.Request object at 0x7fb104026210>.
Saving grant {u'state': u'oHvelCpzosGfJd7ZzCeBvsmRANmipb', u'code': u'yAZZwtCd1IyAeBtHEgg4YTnHl46Ddf'} for <oauthlib.common.Request object at 0x7fb104026210>.
127.0.0.1 - - [25/Feb/2014 14:12:32] "POST /oauth/authorize HTTP/1.1" 302 -
127.0.0.1 - - [25/Feb/2014 14:12:32] "POST /oauth/token HTTP/1.1" 405 -

最佳答案

记录器非常清晰。

Requesting url http://127.0.0.1:5000/oauth/token using method POST.
Request to fetch token completed with status 405.
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>

这意味着您不能 POST 到 http://127.0.0.1:5000/oauth/token。如果您曾经查看过 https://github.com/lepture/example-oauth2-server/blob/master/app.py#L223 中的示例你会发现它不接受 POST 请求。

您可以更改示例:

@app.route('/oauth/token', methods=['POST'])
@oauth.token_handler
def access_token():
    return None

或者您可以使用 GET 方法请求访问 token ,我相信可以在 requests-oauthlib 中设置它。

关于python - flask-oauthlib 服务器不能很好地与 requests-oauthlib 客户端配合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21888461/

相关文章:

php - 如何创建安全的 php 和 javascript api

python - Flask 防止表单注入(inject)

python - 尝试理解 pygame

python - 使用seaborn/matplotlib创建具有特定特征的条形图

c# - 带有oauth的webapi,撤销 token ?

python - Flask-SQLAlchemy:更新一对多关系

python-3.x - 在 Elastic Beanstalk 上部署 Flask 应用程序 : No module named 'application'

python - 在 C++ 中初始化非常大的 vector

python - 对于 beautifulsoup 文件中的所有文件名,返回标签为空

authentication - OAuth 失败了吗?