I have a WordPress site with users, and a separate Flask app with logic for responding to Get/Post requests from the WordPress site.
I am able to get the current user into a JavaScript variable on the WP site and send to the Flask app – however how do I ensure that someone cannot pretend to be a different current user, or make this secure to other potential vulnerabilities?
Is there some way of exposing a token or suchlike to JavaScript on the WP side, which then the Flask app can verify, say by using the WordPress API?
3
Answers
You need to send the data directly from backend side, but if it depends on a frontend trigger, you can then send an AJAX request from JavaScript to backend in WP side.
and without the
nopriv
, This function will be triggered only for logged in users.inside the function, you can get the current user
WP_User
object and the user ID.This is a quick walkthrough of how it should be done. sure, AJAX request will need a nonce check, and sanitization for any passed data, etc.
More details about AJAX request in WP
https://developer.wordpress.org/plugins/javascript/ajax/
https://developer.wordpress.org/plugins/javascript/enqueuing/
https://jackreichert.com/2013/03/24/using-ajax-in-wordpress-development-the-quickstart-guide/
and the WP HTTP API for sending the data to the flask app
https://developer.wordpress.org/plugins/http-api/
We would likely need a little bit more detail to be sure the best way to solve, but it seems there are a few ways of approaching this.
You’ve said that you can get the user id into JavaScript. I’m presuming this means the browser is needing to make the connection to the Flask app. If you have the option of doing this with the WordPress site calling the Flask app directly (server-to-server) you can avoid a lot of hassle.
If you are able to send the request directly from the WordPress server to the Flask app, and the Flask app can check that the source of the request is the WordPress site (either by a shared secret, by checking the IP address the request came from, or just by filtering the traffic to the Flask app to only permit the WordPress server) then do that and you can be sure of the identity of the user making the request.
But if the request has to be made to the Flask app from the browser, then you could do this in a couple of general ways:
You need WordPress Application Passwords. It’s essentially a password for APIs.
In your case, you need to define the application password of the WordPress user in Flask, then Flask can send requests to the WordPress REST API as an authenticated user.