WP REST API: check if user is logged in

The idea is to show or hide some sections of the site in a theme that’s fetching all data from the REST API, using AngularJS.

I thought this check would help me (nonce is passed as header, as suggested by docs):

wp_localize_script('angularjs', 'params', array(
    'nonce' => wp_create_nonce('wp_rest'),
    'nonce_verify' => wp_verify_nonce($_REQUEST['X-WP-Nonce'], 'wp_rest')
));

The nonce parameter works and i can pass it as request header through AngularJS, successfully logging. But the nonce_verify didn’t as expected.

So the question: is there a way to check if an user is logged in when using cookie authentication? Thank you.

EDIT:
I localized nonce’s value cause i needed to get it in this piece of angularJS code. That’s where auth happens:

$httpProvider.interceptors.push(function () {
            return {
                'request' : function (config) {
                    config.headers = config.headers || {};

                    config.headers['X-WP-Nonce'] = params.nonce;

                    return config;
                }
            }
        });

1 Answer
1

You shouldn’t pass your nonce to your JavaScript to verify it, since client side scripts can be easily manipulated. Instead, you should get the nonce from your front-end content, and then pass it to server to verify it.

After verification, you should decide to output content by server, not by your JavaScript file.

Something like this:

if ( is_user_logged_in() ) {
    if ( wp_verify_nonce($_REQUEST['X-WP-Nonce'], 'wp_rest') {
        // Nonce is correct!
    } else {
        // Don't send the data, it's a trap!
    }
}

As a side note, REST API offers its own method to fetch the passed queries. So, you can get it this way in your callback function:

function foobar( \WP_REST_Request $request ) {
    $nonce = $request['X-WP-Nonce'];
}

Leave a Comment