我使用flask创建了一个API,其中使用flask_jwt_extended进行身份验证一切正常。
但是,如果我添加具有 jwt_required 装饰器的资源,则会收到此错误。
File "/Library/Python/2.7/site-packages/flask_jwt/__init__.py", line 176, in decorator
_jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
KeyError: 'JWT_DEFAULT_REALM'
示例资源:
class Endpoint(Resource):
@jwt_required()
def get(self):
return {"State": "Success"}
初始化应用程序:
app = Flask(__name__)
api = Api(app)
添加资源:
api.add_resource(resource_class, "/myEndpoint")
让它工作的唯一方法是在与 API 相同的文件中定义 Endpoint 类。
我认为我需要某种方式将领域传递到端点类中,并使用 jwt_required 上的可选参数来设置领域。
发现了问题,在我导入的资源中
jwt_required
:
from flask_jwt_extended import jwt_required
但是我需要从初始化 JWT 的类中
import jwt_required
。
我认为您忘记初始化 JWT 实例。您可以通过两种方式做到这一点。 第一:
from flask import Flask
from flask_jwt import jwt_required, JWT
from flask_restful import Resource, Api
class Endpoint(Resource):
@jwt_required()
def get(self):
return {"State": "Success"}
app = Flask(__name__)
app.config['SECRET_KEY'] = 'super-secret'
def authenticate(username, password):
# you should find user in db here
# you can see example in docs
user = None
if user:
# do something
return user
def identity(payload):
# custom processing. the same as authenticate. see example in docs
user_id = payload['identity']
return None
# here what you need
jwt = JWT(app, authenticate, identity)
api = Api(app)
api.add_resource(Endpoint, '/myEndpoint')
if __name__ == '__main__':
app.run(debug=True)
app.run(host='0.0.0.0')
第二种方法是更新我们的应用程序配置。只需更改:
jwt = JWT(app, authenticate, identity)
致:
app.config.update(
JWT=JWT(app, authenticate, identity)
)
让我们打开我们的路线。你会看到:
{
"description": "Request does not contain an access token",
"error": "Authorization Required",
"status_code": 401
}
希望有帮助。
由于导入不匹配,我遇到了这个问题。我在使用 JWTManager 等扩展实用程序时,意外地从flask_jwt 导入了它,而不是从flask_jwt_extended 导入jwt_required 装饰器。所以我改变了我的导入:
from flask_jwt import jwt_required
对此:
from flask_jwt_extended import jwt_required