Search code examples
pythonflaskflask-wtformsflask-restless

Flask Restless CSRF exempt authentication URL


I am using Flask Restless 0.17 and Flask JWT for the API portion of an application. In the front-end of the application I am using Flask WTF and its CSRF protection.

This is creating issues with Flask Restless as WTF expects a CSRF token on every view. I am able to get around this on endpoints that I create by exempting the blueprint of the API, but cannot figure out how to apply this to the Flask JWT created /auth URL.

API initilization:

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)

Solution

  • I couldn't figure out how to do it like the above, so I instead turned off WTF CSRF protection and then enable it when we're not on an API endpoint.

    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()