python – Flask-restful API授权。在装饰器中访问current_identity - 代码日志

python – Flask-restful API授权。在装饰器中访问current_identity

我使用烧瓶安静来创建我的API。我已经使用flask-jwt来启用基于JWT的身份验证。现在我需要做授权

我试过把我的授权装潢师。

test.py(/ test 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似乎是空的。所以要间接获取它,我不得不看到jwt_handler的代码,并完成那里的事情。

authorization_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

为什么我不能在authorized_api_user_type装饰器中访问current_identity?在烧瓶中进行授权的方法是什么?

以下是Flask-JWT和Flask-Restful的快速入门的组合。

from flask import Flask
from flask_restful import Resource, Api, abort
from functools import wraps

app = Flask(__name__)
api = Api(app)

from flask_jwt import JWT, jwt_required, current_identity
from werkzeug.security import safe_str_cmp

class User(object):
    def __init__(self, id, username, password):
        self.id = id
        self.username = username
        self.password = password

    def __str__(self):
        return "User(id='%s')" % self.id

users = [
    User(1, 'user1', 'abcxyz'),
    User(2, 'user2', 'abcxyz'),
]

username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}

def authenticate(username, password):
    user = username_table.get(username, None)
    if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
        return user

def identity(payload):
    user_id = payload['identity']
    return userid_table.get(user_id, None)

app.config['SECRET_KEY'] = 'super-secret'

jwt = JWT(app, authenticate, identity)


def checkuser(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if current_identity.username == 'user1':
            return func(*args, **kwargs)
        return abort(401)
    return wrapper

class HelloWorld(Resource):
    decorators = [checkuser, jwt_required()]
    def get(self):
        return {'hello': current_identity.username}

api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(debug=True)

POST

{
    "username": "user1",
    "password": "abcxyz"
}

到localhost:5000 / auth并获取access_token作为响应。

然后GET localhost:5000 /带头

Authorization: JWT `the access_token value above`

你会得到

{
  "hello": "user1"
}

如果您尝试访问localhost:5000 /与user2的JWT令牌,您将获得401。

装饰人员以这种方式包裹:

for decorator in self.decorators:
    resource_func = decorator(resource_func)

https://github.com/flask-restful/flask-restful/blob/master/flask_restful/init.py#L445

所以装饰器数组中的后一个可以提前运行。

更多参考:

https://github.com/rchampa/timetable/blob/master/restful/users.py

https://github.com/mattupstate/flask-jwt/issues/37

http://stackoverflow.com/questions/34217728/flask-restful-api-authorization-access-current-identity-inside-decorator

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:python – Flask-restful API授权。在装饰器中访问current_identity