Flask-Security CSRF token

Jacopo picture Jacopo · Aug 26, 2013 · Viewed 9.9k times · Source

I have a flask app that serves as REST API backend. I would like to implement token based authentication for the backend but in order to do that I need to retrieve the user token. Flask-Security documentation clearly says that to retrieve the token one needs to perform an HTTP POST with the authentication details as JSON data to the authentication endpoint. Unfortunately I don't understand how to retrieve the CSRF token needed to perform such request.

If I use the login page/template provided with the extension the CSRF token is passed to the client in the hidden field in the form. The question is:

how do I retrieve the CSRF token without accessing and parsing the login page, like for example from an angularJS app using $http methods or a mobile app?

Obviously I could avoid using Flask-Security and implement the pieces myself but I'm relatively inexperienced with webapps and I feel I might be approaching this the wrong way.

Answer

Jason picture Jason · Oct 15, 2013

I had a similar use case and ended solving it by following this example from the Flask-WTF docs: https://flask-wtf.readthedocs.org/en/latest/csrf.html#ajax

So by CSRF Protecting the app via CsrfProtect(app), the csrf_token() becomes available in all templates. Then you can easily make it available via a script tag:

<script type="text/javascript">
    var csrftoken = "{{ csrf_token() }}"
</script>

Now add the token to your post data for the Flask-Security /login endpoint.