WordPress REST API calls that depend on the WordPress User

I have a WordPress site, and I have another server.

People login into the wordpress site, then at a later stage browse the other server. On the other server page, there are JS fetch requests getting information from the WordPress REST API. I wish for the WordPress server to return different results depending on which WordPress user they are.

I can hook into wp_login, e.g.

<?php
function login_server_aswell( $user_login, $user ) {
    // tell server user loggin in, get session token back
    // Now can't store the session token in a place where when they browse to the server webpage it can see the cookie
}
add_action('wp_login', 'login_server_aswell', 10, 2);
?>

The problem I have, is after I login, I could tell the other server, this user logged in, give me a sessions token. But then I could only store that session token in a cookie under the wordpress site, not under the servers site, because cookies are not cross site.

Any concepts or overall guidance that can point me in the right direction?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You could hook into the login process in the WP site and create a unique token (stored in meta) for that user on login. The token can then be sent to the other server, that could query the WP API with that token.

You would have to create a custom endpoint that validates the user token. Probably best to have some hash for the userid also.

Furthermore, on logout from the WP site or in some token validation cronjob, this token has to be invalidated for security purpose. Even better, if it’s just one request from the ‘other’ server, invalidate immediately and if on the WP server again, create a new token. So in effect, it’s a CSRF token (nonce) over multiple servers.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x