Function and usage of rest_authorization_required_code() in wordpress

Question

Answers ( 1 )

    0
    2024-01-07T22:21:28+00:00

    The rest_authorization_required_code() function in WordPress is designed to provide a contextual HTTP error code that corresponds to an authorization failure within the context of the WordPress REST API.

    Function Overview:

    • Name: rest_authorization_required_code()
    • Returns: int (either 401 or 403)

    Function Description:

    • This function is used to determine the appropriate HTTP error code to return when an authorization failure occurs.
    • It differentiates between two scenarios:
      1. User Not Logged In: If the user attempting to access a resource via the REST API is not logged in, the function returns an HTTP status code of 401 Unauthorized. This status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.
      2. User Logged In but Lacks Permissions: If the user is logged in but does not have the necessary permissions to access the resource, the function returns an HTTP status code of 403 Forbidden. This status code signifies that the server understands the request but refuses to authorize it.

    Sample Usage:

    function my_custom_rest_endpoint() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return new WP_Error( 'rest_forbidden', esc_html__( 'You do not have permissions to access this resource.', 'my-text-domain' ), array( 'status' => rest_authorization_required_code() ) );
        }
    
        // Rest of the endpoint implementation...
    }
    

    In this example, the function my_custom_rest_endpoint is a custom REST API endpoint. Before proceeding with the implementation, it checks if the current user has the 'manage_options' capability. If not, it returns a WP_Error object, using the rest_authorization_required_code() function to set the appropriate HTTP status code based on whether the user is logged in or not. If the user is logged in but doesn't have the required capability, a 403 error is returned; if the user is not logged in, a 401 error is returned.

Leave an answer