2017-03-23 1 views
0

私は様々なoath2のワークフローをテストしていますが、私は難問です。Authorization Code Grantです。oath2 - Flask(認可ビットバケット)による認可コード付与?

私は、まっすぐな方法でURLをコピー/貼り付けても、正常にトークンを取得できます。 >アクセスリソース -

は私がrequest accesscopy paste given URlenter it in a browseraccept authorizationcopy paste back callback 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) 

私はビットバケットへのアクセスを取得しようとすると、実際のWebアプリを模倣フラスコを使用して、それがアクセスの取得に失敗したことをやろう場合けれども。

マイフラスコアプリの実装サンプルは次のようになります。

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. 

それは次のようになりますそれはoath_stateでやることです。私がoath_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 

それは私がoath_sessionをスキップする場合のように見えるが、それは実際に新しい一致しなくなり、コールバックとREDIRECT_URI上のセッションまたはそのような何かを開始します。

問題が発生する可能性がありますか?

アップデートは

私はsecret_keyでフラスコを更新し、そう何secret_keyに関するないエラーがなくなっていますが、2番目のエラーがまだそこにあります。このエラー:InvalidClientIdError: (invalid_request) redirect_uri does not matchは、コードのこの部分で発生します

... 
... 
bitbucket.fetch_token(
    token_url, 
    client_secret=client_secret, 
    authorization_response=request.url) 
... 
... 

これが関連している場合、私は知らないが、request.urlを印刷し、それは私にこの与える:https://127.0.0.1:5000/callback?state=[bunch_of_random_symbols]を。したがって、最初の部分https://127.0.0.1:5000/callbackは私が消費者をコールバックURLに設定したのとまったく同じです。私には、それは実際に一致しているように見えます。 '

P.S.完全なトレースバックが提供されます。

+0

1. Flaskセッションを使用するには、最初にセッション[秘密鍵](http://flask.pocoo.org/docs/0.12/quickstart/#sessions)を設定する必要があります。 2.最後のトレースバックを延長できますか?このエラーを引き起こしたコード行は何ですか? –

+0

@SergeyShubinは更新された質問を見ます。私はあなたの質問に答えました。 – Andrius

答えて

0

主なエラーの理由は、承認URLには存在しますが、アクセストークンの要求には渡されないredirect_uri引数です。 RFC 6749が説明したよう:

redirect_uri

REQUIRED, if the "redirect_uri" parameter was included in the authorization request as described in Section 4.1.1, and their values MUST be identical.

をですから、redirect_uriとコールバックのOAuthセッションを初期化する必要があります。

@app.route("/callback") 
def callback(): 
    bitbucket = OAuth2Session(
     client_id, state=session['oauth_state'], redirect_uri=redirect_uri 
    ) 

我々はアクセストークンを取得するためredirect_uriを送信する必要がある理由は、開発者の間でかなり一般的な質問です。 Security.StackexchangeのThis discussionが役立つ可能性があります。

最初のエラーについて:

RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret. 

あなたはフラスコセッションでいくつかの情報を保存しようとすると、これが発生しますが、フラスコのアプリケーションのためのsecret keyが設定されていません。

関連する問題