Support » Plugins » Hacks » WP-API not recognizing WordPress login cookie?

Viewing 3 replies - 1 through 3 (of 3 total)
  • I fixed this issue. It turns out that the WP-API will ignore the content of the login cookie and assume an unauthenticated (logged out) request unless the correct value is given in _wpnonce or the HTTP_X_WP_NONCE HTTP header. The relevant code as of this writing is in the rest_cookie_check_errors() function (in wp-includes/rest-api.php. The relevant excerpt is:

    // Determine if there is a nonce.
    $nonce = null;
    
    if ( isset( $_REQUEST['_wpnonce'] ) ) {
        $nonce = $_REQUEST['_wpnonce'];
    } elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
        $nonce = $_SERVER['HTTP_X_WP_NONCE'];
    }
    
    if ( null === $nonce ) {
        // No nonce at all, so act as if it's an unauthenticated request.
        wp_set_current_user( 0 );
        return true;
    }

    As you can see, without a valid nonce passed with the Ajax call in either an HTTP header or the query string of the URL itself, then WordPress calls wp_set_current_user( 0 ), effectively treating the rest of the request as though it was requested by a logged-out user.

    The solution, then, is to ensure your JavaScript is always using the correct nonce value. This can be obtained from the global JavaScript variable wpApiSettings.nonce as long as the WP-API core JavaScript (registered to the wp-api handle) is included on the page. In other words, make sure you enqueue your own JavaScript with array('wp-api') as a dependency.

    Thanks anyways and I hope this helps someone!

    This solved my issue, too, thank you!

    Hello,

    I came across this issue too and needed a whole day to figure it out.

    I found the same solution but I have a question to it. It seems to me, that the JS nonce script is only included in the WP-REST-API Plugin itself and not in the WP Core. In the WP Core there is no skript with: wpApiSettings. So at the moment the only documented way to send authenticated requests to the WP API is to activate the plugin and to inlude the script to get the nonce and send with the request.

    So WordPress anounced big that they now included the Rest API to the core but lacked to include the correct way to make authenticated requests to it?

    So at the moment you can use the Rest API in the core only for displaying public informations and you still need the Plugin for updating etc purposes, right?

    Best regards,

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘WP-API not recognizing WordPress login cookie?’ is closed to new replies.