8

私は別のWebサービスのアカウントを使ってFlaskアプリにログインできるようにしようとしています。私はこのWebサービスのAPIに連絡して、セキュリティトークンを受け取ることができます。制限付きビューにアクセスできるように、このトークンを使用してユーザーを認証するにはどうすればよいですか。Flaskでトークン認証をどのように実装しますか?

私は自分のデータベースにユーザーを保存する必要はありません。私はセッションのためにそれらを認証したいだけです。私はこれがFlask-Securityと@auth_token_requiredデコレータを使って行うことができると信じていますが、ドキュメンテーションはそれほど詳細ではなく、これを実装する方法がわかりません。

EDIT:

@main.route("/login", methods=["GET", "POST"]) 
def login(): 

    payload = {"User": "john", "Password": "password123"} 
    url = "http://webserviceexample/api/login" 
    headers = {'content-type': 'application/json'}) 

    #login to web service 
    r = requests.post(url, headers=headers, json=payload) 
    response = r.json() 

    if (r.status_code is 200): 
     token = response['user']['authentication_token'] 

     # allow user into protected view 

    return render_template("login.html", form=form) 


@main.route('/protected') 
@auth_token_required 
def protected(): 
    return render_template('protected.html') 
+0

トークンを持つユーザーを格納する必要があります。サービスに対するトークンの有効性を確認します。さもなければ、彼らはいつでも第三者サービスに対して訪問者を認証する必要があります。 –

+0

毎回、各セッションを意味しますか?そうであれば、もう一度認証する必要があります。これが問題になる理由はありますか? – Amerikaner

答えて

11

ちょっとそこAmedrikaner:ここ

は、コード例です!

あなたのユースケースは、私たちがこれを自分で実装できるほど簡単なようです。以下のコードでは、ユーザーセッションにトークンを格納し、新しいラッパーをチェックインします。独自のラッパーを作って始めてみましょう。通常、これらはwrappers.pyファイルに入れますが、好きな場所に置くことができます。

def require_api_token(func): 
    @wraps(func) 
    def check_token(*args, **kwargs): 
     # Check to see if it's in their session 
     if 'api_session_token' not in session: 
      # If it isn't return our access denied message (you can also return a redirect or render_template) 
      return Response("Access denied") 

     # Otherwise just send them where they wanted to go 
     return func(*args, **kwargs) 

    return check_token 

クール!

ラッパーを実装しました。トークンをセッションに保存するだけです。スーパーシンプル。

@main.route("/login", methods=["GET", "POST"]) 
def login(): 

    payload = {"User": "john", "Password": "password123"} 
    url = "http://webserviceexample/api/login" 
    headers = {'content-type': 'application/json'}) 

    #login to web service 
    r = requests.post(url, headers=headers, json=payload) 
    response = r.json() 

    if (r.status_code is 200): 
     token = response['user']['authentication_token'] 

     # Move the import to the top of your file! 
     from flask import session 

     # Put it in the session 
     session['api_session_token'] = token 

     # allow user into protected view 

    return render_template("login.html", form=form) 

今、あなたは...このように、

@main.route('/super_secret') 
@require_api_token 
def super_secret(): 
    return "Sssshhh, this is a secret" 

EDIT すごい迫力を@require_api_tokenラッパーを使用して保護されたビューを確認することができます...のは、あなたの関数を変更してみましょう!私はあなたのアプリの設定であなたのSECRET_KEYを設定する必要があることを言及することを忘れました。

SECRET_KEY = "SOME_RANDOM_STRING"のconfig.pyファイルだけが行います。それで...

main.config.from_object(config) 
+0

これはまさに私が探していたものです。ありがとうFブーシュ! – Amerikaner

+0

この2つの要素が必要なだけですか、データベースに対するユーザーの資格情報を検証するための別の機能はないはずですか? –

+0

@EvanBurbidge遅く返事を申し訳ありません。この実装は、他の場所で外部APIに対してユーザーを認証するためのものです。ほとんどの場合、標準的なユーザーログインの流れに従うように、https://flask-login.readthedocs.io/en/latest/ –

関連する問題