我正在使用Flask Restless 0.17和Flask JWT作为应用程序的API部分。在应用程序的前端,我使用Flask WTF及其CSRF保护。
这会给Flask Restless带来问题,因为WTF希望在每个视图上都有一个CSRF令牌。我可以通过免除API的蓝图来解决我创建的端点,但无法弄清楚如何将其应用于Flask JWT created / 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)
答案 0 :(得分:0)
我无法像上面那样弄清楚如何做到这一点,所以我关闭了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()