petrus-jvrensburg
petrus-jvrensburg

Reputation: 1363

Using Flask-Security as part of a REST API

The Flask-Security docs mention JSON/Ajax support for all of the important view endpoints. So it's possible to get all of the buit-in Flask-Security awesomeness by hitting the views with JSON objects.

But, now I'm trying to use it as part of a RESTful API, and it's not working, because it needs a CSRF token, which is necessary for webpages, but not for APIs:

{
    "meta": {
        "code": 400
    },
    "response": {
        "errors": {
            "csrf_token": [
                "CSRF token missing"
            ]
        }
    }
}

What is the best way to get around this?

Upvotes: 2

Views: 3023

Answers (2)

verdverm
verdverm

Reputation: 324

When using a REST API, the prefered method is token based authentication with something like JSON Web Token (JWT). This scheme has a different security landscape because you are not generating HTML on the server side or using cookies. I'm not a security expert, but from what I've read, this means you are not susceptible to Cross Site Request Forgery (CSRF). This is why turning off CSRF tokens in Flask-Security is ok.

Try using PyJWT token based authentication scheme. To get the token, you post credentials to the 'login' endpoint and receive a token in response. You will then have to send the token with each request through HTTP headers. You can often set this globally on the JS side.

Here are a few references:

note: It seems that Flask-JWT uses the python itsdangerous library which hasn't been updated in awhile. There is a discussion here: https://github.com/mattupstate/flask-jwt/issues/10 Again, I'm not a security expert and both libraries seem to be handle the encoding/decoding by default with the same algorithm. PyJWT and Python-Jose are both listed on jwt.io and have extended functionality.

Upvotes: 6

petrus-jvrensburg
petrus-jvrensburg

Reputation: 1363

Okay, figured it out. All it needs is a Flask config variable to be set for the app:

WTF_CSRF_ENABLED = False

Upvotes: 2

Related Questions