No user found when using REST API

This is happening because you are not using nonces. Because you have not provided a nonce with the request, WordPress is treating you as if you are an unauthorized/non-logged in user. This is because wordpress has no way of knowing/validating the users state.

To get this working, you will have to generate a nonce like so:

wp_create_nonce( 'wp_rest' )

and provide it to the app that is making the rest call. Once your app has the nonce value, you would add it to the rest request like so:

headers: {
    'X-WP-Nonce': nonce,
}

Once you’ve done this, WordPress will be able to use the nonce to properly validate the user and conditional checks for permissions will work as expected.

Edit

Per your comment, I thought I would elaborate as this information may be useful for anyone coming across this in the future.

A nonce is defined as a number used once. How wordpress uses them, and why it’s required is the following:

“A nonce is a “number used once” to help protect URLs and forms from certain types of misuse, malicious or otherwise. WordPress nonces aren’t numbers, but are a hash made up of numbers and letters. Nor are they used only once, but have a limited “lifetime” after which they expire. During that time period the same nonce will be generated for a given user in a given context. The nonce for that action will remain the same for that user until that nonce life cycle has completed.

WordPress’s security tokens are called “nonces” despite the above noted differences from true nonces, because they serve much the same purpose as nonces do. They help protect against several types of attacks including CSRF, but do not protect against replay attacks because they aren’t checked for one-time use. Nonces should never be relied on for authentication or authorization, access control. Protect your functions using current_user_can(), always assume Nonces can be compromised.

For an example of why a nonce is used, an admin screen might generate a URL like this that trashes post number 123.”

The TLDR is that nonces are used in conjunction with user authentication cookies provided in the rest request, just like with any server side request. Nonces just provide an additional layer that can be relied on to ensure the user is who they say they are. It’s not a replacement for authentication per se.

For a comprehensive description, see https://codex.wordpress.org/WordPress_Nonces#:~:text=WordPress%20nonces%20aren’t%20numbers,user%20in%20a%20given%20context.