1

I wrote little plugin and I tried to use Rest Api of Wordpress for to communicate admin page to my rest. My problem is : failed rest_cookie_invalid_nonce, return 403 always.

My ajax call :

const form_information_user = jQuery('#form-information-client-login')[0];

let formData = new FormData(form_information_user);

formData.append('_wpnonce',obj_php.nonce)

jQuery.ajax({
    type: 'POST',
    url : obj_php.ajax_url_login,
    cache: false,
    async: true,
    processData: false,
    contentType: false,
    data: formData,
    success: function( data ) {
        // Azioni da eseguire in caso di successo chiamata
        console.log("success: ",data);
    },
    error: function( error ) {
        // Azioni da eseguire in caso di errore chiamata
        console.log("error: ",error);
    }
});

My php file to show view :

class Wp_Diet_Admin_Dashboard{


    private string $plugin_name;
    private string $version;

    public function __construct(string $plugin_name, string $version) {

        $this->plugin_name = $plugin_name;
        $this->version = $version;


        $this->load_scripts();
        $this->load_styles();
        $this->set_scripts_variables();
        $this->load_dashboard();

    }

    public function load_dashboard(): void
    {
        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'views/wp-diet-admin-dashboard.php';
    }
    

    public function load_scripts(): void
    {
        wp_enqueue_script( $this->plugin_name . '-just-validate.js', plugin_dir_url(dirname(__FILE__) ) . 'js/just-validate.js', array('jquery'), $this->version, true );
        wp_enqueue_script( $this->plugin_name . '-dashboard.js', plugin_dir_url(dirname(__FILE__) ) . 'js/dashboard.js', array('jquery'), $this->version, true );
    }

    public function set_scripts_variables() : void
    {

        $obj_php = [
            "ajax_url_registration" => URL_API_V1 . 'form_information_user_registration',
            "ajax_url_login" => URL_API_V1 . 'form_information_user_login',
            "required" => __('Questo campo è obbligatorio','wp-diet'),
            'nonce' => wp_create_nonce( 'wp_rest_dashboard_login' ),
            "error" => __('Valore non valido per questo campo','wp-diet'),
            "error_email" => __('Email non corretta','wp-diet'),
        ];

        wp_localize_script($this->plugin_name . '-dashboard.js','obj_php',$obj_php);

    }        
}

My php file route

class Wp_Diet_Admin_Api{

    private string $plugin_name;
    private string $version;
    private WP_REST_Server $server;

    public function __construct(string $plugin_name, string $version) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
        $this->server = new WP_REST_Server();
    }

    public function load_routes( ): void
    {

        register_rest_route(
            NAMESPACE_V1,
            'form_information_user_login',
            array(
                'methods' => WP_REST_Server::CREATABLE,
                'callback' => array($this, 'form_information_user_login'),
                'permission_callback' => '__return_true',
            )
        );
    }  

    public function form_information_user_login(WP_REST_Request $request)
    {
        $body = $request->get_body_params();
        $email = sanitize_email($body['email']);
        $pass = sanitize_text_field($body['password']);

        $client = new GuzzleHttp\Client();

        $req = $client->request('POST', 'http://www.localhost:3000/registration-success', [
            'form_params' => ['email' => $email, 'password' => $pass]
        ]);

        //jwt-licenza / messaggio d'errore
        $response = json_decode($req->getBody()->getContents(), true);

//        wp_send_json('ok');
        print_r(wp_get_all_sessions());

    }
}

If I not use nonce argument in body request it work but I can't know if the user is logged in, if the request is legal, and I can't manage a session for saving a jwt.

I would like to recognize who is the user who sends me the request and if it is possible to insert the saving of a jwt with relative refresh

Any advice is welcome, thanks for help

Best regalds,

Edit 1:

I try use wp_verify_nonce and the functions failed auth because user in rest api is nobody meanwhile in ajax call the user is logged user. I think is correctly approach, but in this ways I don't know how check auth or user or permission callback.

1 Answer 1

0
  • Check caching/plugins interference

  • Try using:

jQuery.ajax({ type: 'POST', url : obj_php.ajax_url_login, beforeSend: function (xhr) { xhr.setRequestHeader('X-WP-Nonce', obj_php.nonce); },

3
  • Thank your for you time and reply, I tried insert nonce in body, in header, and guide suggest by Wordpress relative cookie auth. Nonce is correct, I print nonce before ajax call and after and it's equal
    – tecnico57
    Commented Sep 2, 2022 at 21:29
  • @tecnico57, try posting this to wordpress.org/support/forum/wp-advanced it's for advanced WP development, you'll maybe get more luck there.
    – wpDev
    Commented Sep 5, 2022 at 14:30
  • Okay I will try, Thanks :)
    – tecnico57
    Commented Sep 6, 2022 at 8:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.