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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With