【问题标题】:Customize flask-security's @auth_token_required unauthorized response自定义 flask-security 的 @auth_token_required 未授权响应
【发布时间】:2019-02-12 19:43:48
【问题描述】:

我是第一次尝试烧瓶,我正在尝试使用基于令牌的身份验证创建一个 rest api。

一切都很好,只是我无法自定义 @auth_token_required 返回的未经授权的响应,这是默认消息:

未经授权

服务器无法验证您是否有权访问该 URL 请求。您要么提供了错误的凭据(例如,错误的 密码),或者您的浏览器不知道如何提供 需要凭据。

我希望它返回一个类似于以下内容的 json 响应:

{
    "code": 401,
    "message": "Unauthorized message"
}

到目前为止,我已经尝试使用以下方法覆盖 unauthorized_handler

@app.login_manager.unauthorized_handler
def unauthorized():
    // code goes here

但它似乎不适用于 @auth_token_required 装饰器。

【问题讨论】:

    标签: python flask flask-security


    【解决方案1】:

    参考pip的响应,Flask Security内部使用flask login来实现回调。因此当我们向Flask security注册回调处理程序时,我们得到调用堆栈超出响应。

    app.security.unauthorized_handler(unauth_handler)

    因此请使用 Flask 登录进行注册

    app.login_manager.unauthorized_handler(unauth_handler)

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      这是我的代码;它似乎工作!

      import json
      
      from flask import Reponse
      
      
      def unauth_handler():
          return Response(json.dumps({'unauthorized': True}), 401)
      
      app.security.unauthorized_handler(unauth_handler)
      

      这里有一个更完整的例子来说明这个被调用的地方,以防万一与下面的错误有关。

      def setup_app(app):
          config(app)
      
          # database init, allows the DB to be available in core but setup per application.
          db.init_app(app)
      
          # bcrypt, again available from core.
          bcrypt.init_app(app)
      
          # setup assets
          app.assets_env = Environment(app)
      
          # login system
          app.user_datastore = SQLAlchemyUserDatastore(db, User, Role)
          app.security = security.init_app(app, app.user_datastore)
      
          def unauth_handler():
              return Response(ejson.dumps({'unauthorized': True}), 401)
      
          app.security.unauthorized_handler(unauth_handler)
      
          logger(app)
          jinja_filters(app)
          assets(app)
          modules(app)
      

      然后我将 app 传入 init 的 setup 函数中。

      【讨论】:

      • 尝试了这段代码,得到了超出最大调用堆栈的错误。
      • 嗯。让我再看一下我的代码,我好像记得改过。
      【解决方案3】:

      更新上述答案

      from flask import response, jsonify
      from flask_security.decorators import _get_unauthorized_response
      
      user_datastore = SQLAlchemyUserDatastore(db, User, Role)
      security = Security()
      security_state = security.init_app(app, user_datastore)
      
      def unauth_handler():
          if request.is_json:
              return jsonify({'status': False, 'message': 'Unauthorized!'}), 401, {'Content-Type': 'application/json'}
          else:
              return _get_unauthorized_response()
      
      security_state.unauthorized_handler(unauth_handler)
      

      【讨论】:

        猜你喜欢
        • 2021-10-01
        • 1970-01-01
        • 2019-01-07
        • 1970-01-01
        • 2021-02-02
        • 2021-07-27
        • 2019-01-16
        • 1970-01-01
        • 2016-04-23
        相关资源
        最近更新 更多