custom REST endpoints and application passwords

If you want to use application passwords to authenticate requests to your RESTful endpoints, you can modify your permission_callback function to check for the presence and validity of an application password instead of a user’s credentials.

To do this, you can use the wp_check_application_passwords function, which was introduced in WordPress 5.6. This function takes an application password and a user ID (or a username) and returns a WP_Error object if the password is invalid or expired, or an array with information about the password if it’s valid. Here’s an example of how you could modify your permission_callback function to use application passwords:

function my_rest_permission_callback( $request ) {
    $app_password = $request->get_header( 'X-WP-Application-Password' );

    if ( empty( $app_password ) ) {
        return new WP_Error( 'rest_forbidden', __( 'Authentication required.' ), array( 'status' => 401 ) );
    }

    $user_id = get_current_user_id(); // or get the user ID from the request data

    $result = wp_check_application_passwords( $user_id, $app_password );

    if ( is_wp_error( $result ) ) {
        return new WP_Error( 'rest_forbidden', $result->get_error_message(), array( 'status' => 403 ) );
    }

    // Here you can do additional checks or data processing based on the password information
    // ...

    return true; // Access granted
}

In this example, the permission_callback function retrieves the X-WP-Application-Password header from the request, which should contain the application password provided by the client. If the header is empty, the function returns a 401 Unauthorized error.

The function then calls wp_check_application_passwords with the current user ID and the application password, and checks if the result is an error. If so, the function returns a 403 Forbidden error with the message from the WP_Error object. Otherwise, the function assumes that the password is valid and returns true to allow access to the endpoint.

You can customize this code to fit your specific needs, such as checking additional information in the password result or handling errors differently. Note that you need to create and manage application passwords in the WordPress administration area, under the user profile of the user who will be making the requests.