WordPress nonce middleware for snicco/http-routing
This middleware for the snicco/http-routing
component will eliminate your WordPress nonce problems once and for all.
Stop validating nonces manually in each controller.
Stop forgetting to validate nonces.
Stop coupling your controller code to your views through nonce actions.
There is a better way.
composer require snicco/wp-nonce-middleware
Add the VerifyWPNonce
middleware to your global middleware.
This middleware does the following for every request:
- Unsafe requests (
POST
,PATCH
,DELETE
, etc) will be checked for a valid WordPress nonce in the request body usingwp_verify_nonce
. If no valid nonce is found a401 HTTPException
will be thrown. - For READ requests and instance of
WPNonce
will be added to the view data if the returned response is aViewResponse
.
In your views you can use the WPNonce
instance like so:
Posting to the same location where the form is located:
<?php
/**
* @var Snicco\Middleware\WPNonce\WPNonce $wp_nonce
*/
?>
<form method="POST">
<?= $wp_nonce() ?>
<button type="submit">Submit</button>
</form>
Posting to a route url or hard-coded url that is different from the current location:
<?php
/**
* @var Snicco\Middleware\WPNonce\WPNonce $wp_nonce
* @var Snicco\Component\HttpRouting\Routing\UrlGenerator\UrlGenerator $url
*/
$route_url = $url->toRoute('route1', ['param1' => 'foo']);
?>
<form method="POST" action="<?= $route_url ?>">
<?= $wp_nonce($route_url) ?>
<button type="submit">Submit</button>
</form>
Now forget about WordPress nonces forever. If a request reaches your controller it has a valid nonce.
This repository is a read-only split of the development repo of the Snicco project.
This is how you can contribute.
Please report issues in the Snicco monorepo.
If you discover a security vulnerability, please follow our disclosure procedure.