【问题标题】:Adding resources with jwt_required?使用 jwt_required 添加资源?
【发布时间】:2017-12-09 02:45:54
【问题描述】:

我使用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 上的可选参数来设置领域。

【问题讨论】:

    标签: python flask jwt flask-restful


    【解决方案1】:

    我想你忘了初始化JWT 实例。您可以通过 2 种方式进行操作。 第一

    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
    }
    

    希望对你有帮助。

    【讨论】:

    • 感谢 Danila,JWT 已初始化,我的示例中没有显示。
    【解决方案2】:

    在我导入jwt_required的资源中发现了问题:

    from flask_jwt_extended import jwt_required
    

    但是我需要在初始化 JWT 的类中import jwt_required

    【讨论】:

    • 这不是意味着循环依赖吗,如果您使用的是 Blue Prints 会怎样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多