OAuth2 is a common method for API authentication. What does it mainly help with in WordPress REST API?
Think about how OAuth2 helps users keep their passwords safe when using third-party apps.
OAuth2 lets users authorize apps to access their data without giving out their password, improving security and user control.
Consider a WordPress REST API route that requires authentication. What will the server respond if you call it without any authentication?
Think about what HTTP status code means 'you need to log in first'.
Protected routes require authentication. Without it, WordPress returns a 401 Unauthorized error to indicate access is denied.
Choose the code snippet that properly enables Basic Authentication for WordPress REST API requests.
Look for the filter hook that checks if the PHP_AUTH_USER is empty and returns an error if so.
The 'rest_authentication_errors' filter lets you check authentication. Returning a WP_Error with status 401 denies access properly.
Given the following code snippet inside a REST API callback, what will be the output if the user is not logged in?
<?php
function my_api_callback() {
if (!is_user_logged_in()) {
return new WP_Error('rest_forbidden', 'You must be logged in.', array('status' => 403));
}
return array('message' => 'Welcome!');
}
?>Think about what happens when the user is not logged in and the function returns a WP_Error.
The function returns a WP_Error with status 403, which the REST API converts to a JSON error response with code and message.
Examine the code below. It is intended to restrict access to authenticated users only. Why does it fail to do so?
add_filter('rest_authentication_errors', function($result) {
if (!empty($_SERVER['PHP_AUTH_USER'])) {
return true;
}
return $result;
});Check what returning true or an error from this filter means for access control.
In 'rest_authentication_errors', returning true means no error occurred, so access is granted. To block access, you must return a WP_Error instead.