我正在使用Flask Restless 0.17和Flask JWT作为应用程序的API部分。在应用程序的前端,我正在使用Flask WTF及其CSRF保护。
这给Flask Restless带来了问题,因为WTF期望在每个视图上都有一个CSRF令牌。我能够通过免除 API 的蓝图在我创建的端点上解决此问题,但无法弄清楚如何将其应用于 Flask JWT 创建的/auth URL。
API 初始化:
def init_app(app):
def authenticate(username, password):
user = User.query.filter_by(username=username).scalar()
if user and username == user.username and
User.check_password(user, password):
return user
return None
def load_user(payload):
user = User.query.filter_by(id=payload['identity']).scalar()
return user
jwt = JWT(app, authenticate, load_user)
@jwt_required()
def auth_func(**kw):
pass
manager = flask_restless.APIManager(app, flask_sqlalchemy_db=db)
bp = manager.create_api_blueprint(
MyModel,
methods=['GET'],
url_prefix='/api/v1',
preprocessors=dict(GET_SINGLE=[auth_func],
GET_MANY=[auth_func]),
results_per_page=10,
)
# Here I can exempt this API endpoint.
# But how do I exempt /auth which is created by Flask JWT?
csrf_protect.exempt(bp)
app.register_blueprint(bp)
我不知道如何像上面那样做,所以我关闭了 WTF CSRF 保护,然后在我们不在 API 端点上时启用它。
settings.py
WTF_CSRF_CHECK_DEFAULT = False
app.py
def register_csrf(app):
"""
Only enable CSRF protection on URLs that are not API related.
:param app: The app
"""
@app.before_request
def check_csrf():
if request.endpoint != 'api':
csrf_protect.protect()