【发布时间】:2016-03-17 00:33:41
【问题描述】:
我使用 flask-restful 来创建我的 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 在那个装饰器中似乎是empty。因此,为了间接获得它,我必须查看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-restful 中进行授权的正确方法是什么?
【问题讨论】:
标签: python flask flask-restful flask-jwt