What is the correct way to secure a Wordpress Rest API?

built

//
BuSo Pro
Boot Camp
Joined
Jan 23, 2015
Messages
1,669
Likes
1,435
Degree
4
What would the best approach be for securing a POST request to a custom end point?

I know how to use jwts etc in javascript but what is the recommended way to do it in Wordpress?
 

BCN

$$$$ ¯\_(ツ)_/¯ $$$$
Joined
Dec 26, 2015
Messages
260
Likes
264
Degree
1
Are you accessing it from the same domain? If yes, generate a nonce and send it along as a X-WP-Nonce header, if not use a JWT plugin (i.e. if you access from a different domain and don't have a cookie).

When I write plugins, I just add a nonce from PHP accessible via JS, and add it to headers (as most stuff would be React/plain JS inside WP-admin). This is what WP recommends too, if you're using it on the same domain.

Let me know, I can send over some code if you need.

Edit: for your custom endpoints, there's a permission callback that returns a boolean. You can do any check you need there (user logged in, user can edit posts ...).
 

built

//
BuSo Pro
Boot Camp
Joined
Jan 23, 2015
Messages
1,669
Likes
1,435
Degree
4
Are you accessing it from the same domain? If yes, generate a nonce and send it along as a X-WP-Nonce header, if not use a JWT plugin (i.e. if you access from a different domain and don't have a cookie).

When I write plugins, I just add a nonce from PHP accessible via JS, and add it to headers (as most stuff would be React/plain JS inside WP-admin). This is what WP recommends too, if you're using it on the same domain.

Let me know, I can send over some code if you need.

Edit: for your custom endpoints, there's a permission callback that returns a boolean. You can do any check you need there (user logged in, user can edit posts ...).

Yeah I'm only really accessing from the gutenberg editor. Is the nonce you are talking about the
JavaScript:
wpApiSettings.nonce
that's available?

Some demo code would be awesome, because the Wordpress docs around this is a bit confusing for me, I was trying to use this function but dont think its the right one https://developer.wordpress.org/reference/functions/rest_cookie_check_errors/
 

BCN

$$$$ ¯\_(ツ)_/¯ $$$$
Joined
Dec 26, 2015
Messages
260
Likes
264
Degree
1
Hey, I'll take some code out of my project and send over! :smile: