27

私はフラスコ・レストフルを使って API を作成しています。flask-jwtに基づいて認証を有効にするために使用しましたJWT。次に、承認を行う必要があります。

認証デコレータを入れてみました。

test.py (/テスト API)

from flask_restful import Resource
from flask_jwt import jwt_required

from authorization_helper import authorized_api_user_type


class Test(Resource):

    decorators = [jwt_required(), authorized_api_user_type()]

    def get(self):
        return 'GET OK'

    def post(self):
        return 'POST OK'

基本的に基本的な承認を処理するには、アクセスcurrent_identityしてそのタイプを確認する必要があります。次に、そのタイプに基づいて、ユーザーが API / リソースへのアクセスを許可されているかどうかを判断します。

しかし、そのデコレータにあるcurrent_identityようです。emptyしたがって、間接的に取得するには、コードを見て、jwt_handlerそこで行われたことを実行する必要がありました。

authentication_helper.py

from functools import wraps
from flask_jwt import _jwt, JWTError
import jwt
from models import Teacher, Student

def authorized_api_user_type(realm=None, user_type='teacher'):
    def wrapper(fn):
        @wraps(fn)
        def decorator(*args, **kwargs):
            token = _jwt.request_callback()

            if token is None:
                raise JWTError('Authorization Required', 'Request does not contain an access token',
                               headers={'WWW-Authenticate': 'JWT realm="%s"' % realm})

            try:
                payload = _jwt.jwt_decode_callback(token)
            except jwt.InvalidTokenError as e:
                raise JWTError('Invalid token', str(e))

            identity = _jwt.identity_callback(payload)
            if user_type == 'student' and isinstance(identity, Student):
                return fn(*args, **kwargs)
            elif user_type == 'teacher' and isinstance(identity, Teacher):
                return fn(*args, **kwargs)
            # NOTE - By default JWTError throws 401. We needed 404. Hence status_code=404
            raise JWTError('Unauthorized',
                           'You are unauthorized to request the api or access the resource',
                           status_code=404)
        return decorator
    return wrapper

デコレータcurrent_identityでアクセスできないのはなぜですか? authorized_api_user_typeフラスコレストフルで承認を行う正しい方法は何ですか?

4

3 に答える 3

5

私の現在のソリューションは次のようになります。

@app.before_request
def detect_something():
    header = request.headers.get('Authorization')
    if header:
        _, token = header.split()
        request.identity = identity(jwt.decode(token,
                                               app.config['SECRET_KEY']))

その後、 経由でデコレータの ID にアクセスできますrequest.identitycurrent_identityそして、コードからあらゆる場所を削除しました。それはまだ厄介な方法です。

于 2016-03-16T19:07:12.220 に答える