rest_cookie_check_errors

Checks for errors when using cookie-based authentication.

Description

(WP_Error|mixed|bool) rest_cookie_check_errors( (WP_Error|mixed) $result ); 

WordPress' built-in cookie authentication is always active for logged in users. However, the API has to check nonces for each request to ensure users are not vulnerable to CSRF.

Returns (WP_Error|mixed|bool)

WP_Error if the cookie is invalid, the $result, otherwise true.

Parameters (1)

0. $result (WP_Error|mixed)
Error from another authentication handler, null if we should handle it, or another value if not.

Usage

  1. if ( !function_exists( 'rest_cookie_check_errors' ) ) { 
  2. require_once ABSPATH . WPINC . '/rest-api.php'; 
  3. $result = null; 
  4.  
  5. // NOTICE! Understand what this does before running. 
  6. $result = rest_cookie_check_errors($result); 
  7.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/rest-api.php  
  1. function rest_cookie_check_errors( $result ) { 
  2. if ( ! empty( $result ) ) { 
  3. return $result; 
  4.  
  5. global $wp_rest_auth_cookie, $wp_rest_server; 
  6.  
  7. /** 
  8. * Is cookie authentication being used? (If we get an auth 
  9. * error, but we're still logged in, another authentication 
  10. * must have been used). 
  11. */ 
  12. if ( true !== $wp_rest_auth_cookie && is_user_logged_in() ) { 
  13. return $result; 
  14.  
  15. // Determine if there is a nonce. 
  16. $nonce = null; 
  17.  
  18. if ( isset( $_REQUEST['_wpnonce'] ) ) { 
  19. $nonce = $_REQUEST['_wpnonce']; 
  20. } elseif ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) { 
  21. $nonce = $_SERVER['HTTP_X_WP_NONCE']; 
  22.  
  23. if ( null === $nonce ) { 
  24. // No nonce at all, so act as if it's an unauthenticated request. 
  25. return true; 
  26.  
  27. // Check the nonce. 
  28. $result = wp_verify_nonce( $nonce, 'wp_rest' ); 
  29.  
  30. if ( ! $result ) { 
  31. return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie nonce is invalid' ), array( 'status' => 403 ) ); 
  32.  
  33. // Send a refreshed nonce in header. 
  34. $wp_rest_server->send_header( 'X-WP-Nonce', wp_create_nonce( 'wp_rest' ) ); 
  35.  
  36. return true;