ajax – Should wordpress nonce be placed in html form or in javascript file

Question

This example is specifically related to woocommerce but apparently the same question also applies to wordpress. Hence I believe this question is relevant to this forum. Here goes the example:

I create a customized woocommerce theme with special cart and checkout ajax handlers.

Woocommerce has implemented cart and checkout ajax endpoints with special security token called a nonce. I see two methods of implementing nonce in the theme:

1) Insert nonce field into html form element:

<?php wp_nonce_field( 'woocommerce-process_checkout' ); ?>

The nonce is then loaded in javascript method from the form.

2) Insert nonce directly into javascript method that handles the request:

functions.php

wp_enqueue_script('checkout', get_template_directory_uri().'/js/checkout.js', array('jquery'), '', true);  
wp_localize_script('checkout', 'wc_rest_api_checkout', array(
  'url' => get_site_url(null, '/?wc-ajax='),
  'nonce' => wp_create_nonce('woocommerce-process_checkout')
));

checkout.js

data = {};
data['_wpnonce'] = wc_rest_api_checkout.nonce;
$.ajax({
  type: 'POST',
  url: wc_rest_api_checkout.url+'checkout',
  dataType: 'json',
  data: data,
  success: function(res) {
    console.log(res);
    return;
  },
  error: function(res) {
    console.log('CheckoutHandler.sendOrder: error occured');
    console.log(res);
    return;
  }
});

Which of these two methods is recommended regarding the security?

0
user46581 2 months 2021-12-02T14:35:13-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse