How to add additional http header to a wp_error rest response

WP_REST_Response extends WP_HTTP_Response class, which has a header() method for setting headers.

Using the rest_request_after_callbacks filter should allow setting the header, but will need to duplicate the functionality of WP_REST_Server->error_to_response(), which at time of writing calls rest_convert_error_to_response(), so that’s easy enough.

Here’s what I think this will end up looking like (untested).

add_filter( 'rest_request_before_callbacks', static function ( $response, $handler, $request ) {
    if ( $request->get_header( 'authorization' ) ) {
        return $response;
    }

    return new WP_Error( 'authorization', 'Unauthorized access.', array( 'status' => 401 ) );
}, 10, 3 );

add_filter( 'rest_request_after_callbacks', static function ( $response ) {
    if ( ! is_wp_error( $response ) ) {
        return $response;
    }

    // Only apply to specific error messages.
    if ( 'authorization' !== $response->get_error_code() ) {
        return $response;
    }

    $response = rest_convert_error_to_response( $response );

    $response->header( 'WWW-Authenticate', '' );

    return $response;
} );