snicco/wp-nonce-middleware

v1.9.0 2023-09-20 12:36 UTC

README

codecov Psalm Type-Coverage Psalm level PhpMetrics - Static Analysis PHP-Versions

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.

Installation

composer require snicco/wp-nonce-middleware

Usage

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 using wp_verify_nonce. If no valid nonce is found a 401 HTTPException will be thrown.
  • For READ requests and instance of WPNonce will be added to the view data if the returned response is a ViewResponse.

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.

Contributing

This repository is a read-only split of the development repo of the Snicco project.

This is how you can contribute.

Reporting issues and sending pull requests

Please report issues in the Snicco monorepo.

Security

If you discover a security vulnerability, please follow our disclosure procedure.