Python oath2-使用Flask授予授权码(访问bitbucket)?
我正在测试各种Python oath2-使用Flask授予授权码(访问bitbucket)?,python,flask,oauth-2.0,Python,Flask,Oauth 2.0,我正在测试各种oath2工作流程,我正在努力尝试的是Authorization code Grant 如果我直接复制/粘贴URL,我可以成功获得令牌 我的意思是请求访问,复制粘贴给定URl,在浏览器中输入它,接受授权,复制粘贴回回叫URl->访问资源。如本例所示: from requests_oauthlib import OAuth2Session class ClientSecrets: """ The structure of this class follows Go
oath2
工作流程,我正在努力尝试的是Authorization code Grant
如果我直接复制/粘贴URL,我可以成功获得令牌
我的意思是请求访问
,复制粘贴给定URl
,在浏览器中输入它
,接受授权
,复制粘贴回回叫URl
->访问资源。如本例所示:
from requests_oauthlib import OAuth2Session
class ClientSecrets:
"""
The structure of this class follows Google convention for `client_secrets.json`:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
Bitbucket does not emit this structure so it must be manually constructed.
"""
client_id = "myid"
client_secret = "mysecret"
auth_uri = "https://bitbucket.org/site/oauth2/authorize"
token_uri = "https://bitbucket.org/site/oauth2/access_token"
server_base_uri = "https://api.bitbucket.org/"
def main():
c = ClientSecrets()
# Fetch a request token
bitbucket = OAuth2Session(c.client_id)
# Redirect user to Bitbucket for authorization
authorization_url = bitbucket.authorization_url(c.auth_uri)
print('Please go here and authorize: {}'.format(authorization_url[0]))
# Get the authorization verifier code from the callback url
redirect_response = raw_input('Paste the full redirect URL here:')
# Fetch the access token
bitbucket.fetch_token(
c.token_uri,
authorization_response=redirect_response,
username=c.client_id,
password=c.client_secret)
# Fetch a protected resource, i.e. user profile
r = bitbucket.get(c.server_base_uri + '1.0/user')
print(r.content)
不过,如果我尝试使用Flask模拟实际的web应用程序来访问bitbucket,它将无法访问
我的Flask应用程序实现示例如下所示:
from flask import Flask, redirect, request, session
from requests_oauthlib import OAuth2Session
app = Flask(__name__)
client_id = 'myid'
client_secret = 'mysecret'
authorization_base_url = 'https://bitbucket.org/site/oauth2/authorize'
token_url = 'https://bitbucket.org/site/oauth2/access_token'
redirect_uri = 'https://127.0.0.1:5000/callback'
@app.route('/login')
def login():
oauth2 = OAuth2Session(client_id, redirect_uri=redirect_uri)
authorization_url, state = oauth2.authorization_url(
authorization_base_url,
)
# State is used to prevent CSRF, keep this for later.
session['oauth_state'] = state
return redirect(authorization_url)
@app.route("/callback")
def callback():
bitbucket = OAuth2Session(client_id, state=session['oauth_state'])
bitbucket.fetch_token(
token_url,
client_secret=client_secret,
authorization_response=request.url)
return bitbucket.get('some_resource_url').content
if __name__ == '__main__':
# Certificate and key files.
context = ('cert/server.crt', 'cert/server.key')
app.run(debug=True, ssl_context=context)
若我像示例中那个样运行应用程序,那个么当我试图访问URL:https://127.0.0.1:5000/login
File "/home/oerp/python-programs/flask-app/bitiface/test.py", line 23, in login
session['oauth_state'] = state
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/werkzeug/local.py", line 350, in __setitem__
self._get_current_object()[key] = value
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/flask/sessions.py", line 130, in _fail
raise RuntimeError('The session is unavailable because no secret '
RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.
看起来像是有什么事情要做了。如果我评论誓言\u state
分配并尝试像以前一样运行应用程序。然后我得到这个错误:
Traceback (most recent call last):
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/flask/app.py", line 1994, in __call__
return self.wsgi_app(environ, start_response)
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/oerp/python-programs/flask-app/bitiface/test.py", line 33, in callback
authorization_response=request.url)
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/requests_oauthlib/oauth2_session.py", line 244, in fetch_token
self._client.parse_request_body_response(r.text, scope=self.scope)
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/clients/base.py", line 409, in parse_request_body_response
self.token = parse_token_response(body, scope=scope)
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 376, in parse_token_response
validate_token_parameters(params)
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 383, in validate_token_parameters
raise_from_error(params.get('error'), params)
File "/home/oerp/python-programs/flask-app/bitiface/venv/lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/errors.py", line 325, in raise_from_error
raise cls(**kwargs)
InvalidClientIdError: (invalid_request) redirect_uri does not match
看起来,如果我跳过了宣誓会话,那么它实际上会在回调时启动新会话,重定向uri将不匹配或类似的情况
有人知道可能是什么问题吗?
更新
我用secret\u key
更新了烧瓶,所以关于nosecret\u key
的错误消失了,但第二个错误仍然存在。此错误:invalidClientError:(无效请求)重定向uri不匹配
在代码的此部分引发:
...
...
bitbucket.fetch_token(
token_url,
client_secret=client_secret,
authorization_response=request.url)
...
...
我不知道这是否相关,但打印request.url
,它会告诉我:https://127.0.0.1:5000/callback?state=[一堆随机符号]
。所以第一部分https://127.0.0.1:5000/callback
与我在消费者上设置的回调URL完全相同。在我看来,它实际上是匹配的。
`
另外,提供了完整的回溯。主要错误的原因是
重定向\u uri
参数,该参数存在于授权URL中,但未在访问令牌请求中传递。如前所述:
重定向\u uri
如第4.1.1节所述,如果授权请求中包含“redirect_uri”参数,且其值必须相同,则为必填项
因此,您需要使用重定向\u uri
初始化回调OAuth会话:
@app.route("/callback")
def callback():
bitbucket = OAuth2Session(
client_id, state=session['oauth_state'], redirect_uri=redirect_uri
)
在开发人员中,这是一个很常见的问题,为什么我们需要发送redirect\u uri
来获取访问令牌。关于安全性。Stackexchange可能会有所帮助
关于第一个错误:
RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.
当您试图在Flask会话中保存某些信息,但未设置Flask应用程序时,会引发此问题。1。首先,您需要设置会话以使用Flask会话。2.你能延长最后一次追踪吗?是哪行代码导致了这个错误?@SergeyShubin查看更新的问题。我已经回答了你的问题。