• Resolved dazz17

    (@dazz17)


    I’m creating a wordpress plugin where i’m registering some rest routes. I’m localizing a nonce value. I’ve developed the plugin’s front end in vue js. My question is, Will the nonce work even if the rest api is called from another domain (i.e) when the rest api is called from another local vue cli instance running locally?

Viewing 11 replies - 1 through 11 (of 11 total)
  • If you are using a nonce, it has to be generated on the server, passed to the client, and returned to the server for verification.

    Thread Starter dazz17

    (@dazz17)

    Thanks for you replay Joy, But i’m doing the same you suggested but it still says nonce invalid. The only difference is my javascript files are in a different domain not inside the wordpress plugin. I’ve copied the nonce value from the server and I sent it through the api calls for verification. Also I’ve created the nonce value using the action “wp_rest” as mentioned in the documentation

    Moderator bcworkz

    (@bcworkz)

    It’s not clear where your nonce is actually coming from. The domain name is not the issue. The nonce must come from the same WP instance that will process the API request. Each has unique security salts and clock values. You cannot utilize nonces from a different server because these values will be different.

    Thread Starter dazz17

    (@dazz17)

    Cool, I understand that. So the nonce created in the server A is sent to the server B. The server B is now trying to make an api call to the server A using the same nonce which came from server A. Since the nonce is originally created from the server A, Will the request be allowed or will it be forbidden due to invalid nonce error?

    Moderator bcworkz

    (@bcworkz)

    Right, allowed. If you’re still having trouble maybe you should show us how you create and send nonces.

    Thread Starter dazz17

    (@dazz17)

    @bcworkz Thanks for confirming.
    Creating nonce and registering rest routes

    add_action('admin_enqueue_scripts','addScripts');
    function addScripts() { 
        wp_enqueue_script('axios', 'https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js', 1);
        wp_enqueue_script('vue',plugin_dir_url(__FILE__).'MiddleMan.js',1);
        fp_localize_script();
    }
    function fp_localize_script()
    {
        $plugin_config = array(
            'allowedOrigin' => $_SERVER['SERVER_NAME'],
            'allowedDevOrigin' => $_SERVER['HTTP_HOST'],
            'ajaxurl' => admin_url('admin-ajax.php', 'relative'),
            'nonce'=> wp_create_nonce('wp_rest'),
        );
        wp_localize_script( 'vue', 'fpPluginConfig', $plugin_config );
    }
    function my_customize_rest_cors() {
    	remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
    	add_filter( 'rest_pre_serve_request', function( $value ) {
    		header( 'Access-Control-Allow-Origin: *' );
            header( 'Access-Control-Allow-Headers: X-WP-NONCE, Content-Type');
    		return $value;
    	} );
    }
    add_action( 'rest_api_init', 'my_customize_rest_cors', 15 );
    add_action( 'rest_api_init', function () {
        register_rest_route(
            'fpwp',
            'posts/',
            array(
                'methods' => 'POST',
                'permission_callback' => function () {
                    return current_user_can('edit_others_posts');
                },
                'callback' => 'newEndPointCallback'
            ) );
          register_rest_route(
            'fpwp',
            'authmeth/',
            array(
                'methods' => 'POST',
                'permission_callback' => function () {
                    return current_user_can('edit_others_posts');
                },
                'callback' => 'accessFirstPageCallback'
            ));
      } );

    I console.log this nonce created here and copy that to vue instance from which the api calls are made.

    The vue js code goes as below.

    async getAccessToken () {
        let headers = {
          'X-WP-NONCE': the_actual_nonce_value_which_was_copied
        };
        try {
          const response = await Axios.post('https://localhost/wordpress/wp-json/fpwp/authmeth/', {}, { headers: headers });
          return response;
        } catch (error) {
          throw error;
        }
      }

    The reason why I was doubting the origin issue was because the nonce was validated perfectly when I enqueued the vue js build files into the wordpress plugin. Only when the api call was made from a different origin, the nonce was invalid.

    • This reply was modified 4 years, 11 months ago by dazz17.
    Moderator bcworkz

    (@bcworkz)

    Oh, you manually copied it over into something else? No that doesn’t work, as you’ve discovered ?? Another component in creating a nonce is the auth session. If you copy it over you have a different auth session. The client app receiving the nonce from the server needs to be the one making the API request.

    Thread Starter dazz17

    (@dazz17)

    Oh damn, So my actual use case is creating an api inside a wordpress plugin and calling that api from another website. Thank you so much for time @bcworkz . Do know any solutions for my above use case? also is there any way to communicate with the wordpress server from an external server ?

    Moderator bcworkz

    (@bcworkz)

    No problem, the auth session bit caught me by surprise. I’m learning too ?? You’d need to relay everything back through the other server. More of a straight back and forth routing instead of a ring. Server A > Server B > Client > Server B > Server A etc. Each leg using its own auth credentials to talk with its immediate component.

    Thread Starter dazz17

    (@dazz17)

    Thank you @bcworkz ?? .

    Moderator bcworkz

    (@bcworkz)

    You’re welcome. Happy coding!

Viewing 11 replies - 1 through 11 (of 11 total)
  • The topic ‘Nonce invalid’ is closed to new replies.