How to get current logged in user using WordPress Rest Api?

From the Authentication chapter, in the REST API Handbook:

Cookie authentication is the basic authentication method included with
WordPress. When you log in to your dashboard, this sets up the cookies
correctly for you, so plugin and theme developers need only to have a
logged-in user.

However, the REST API includes a technique called nonces to avoid CSRF
issues. This prevents other sites from forcing you to perform actions
without explicitly intending to do so. This requires slightly special
handling for the API.

For developers using the built-in Javascript API, this is handled
automatically for you. This is the recommended way to use the API for
plugins and themes. Custom data models can extend wp.api.models.Base
to ensure this is sent correctly for any custom requests.

For developers making manual Ajax requests, the nonce will need to be
passed with each request. The API uses nonces with the action set to
wp_rest. These can then be passed to the API via the _wpnonce data
parameter (either POST data or in the query for GET requests), or via
the X-WP-Nonce header.

Here’s a GET example:

https://example.tld/wp-json/wp/v2/users/me?_wpnonce=9467a0bf9c

or in your case:

https://example.tld/wp-json/custom/login/?_wpnonce=9463a0bf9c

where the nonce is created from

wp_create_nonce( 'wp_rest' );

So most likely you forgot about the nonce part when testing your custom endpoint.

Hope it helps!

Leave a Comment