Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-Security CSRF token

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.

like image 203
Jacopo Avatar asked Aug 26 '13 03:08

Jacopo


2 Answers

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.

like image 127
Jason Avatar answered Sep 28 '22 07:09

Jason


Well, there is a simple way. Visit. A configuration item WTF_CSRF_ENABLED could be set to False to disable the csrf. Then everything goes as you wish.

like image 22
Kinorsi Avatar answered Sep 28 '22 07:09

Kinorsi