Authenticate rest API except for contact-form-7

Question

I have a contact-form plugin that requires access to the rest api. My original settings were to disallow access to rest api except for administrators and editors.

However, to allow the contact-form to work I need to remove rest api authentication for contact-form hence I modified the authentication code such that authentication will not be required if request url includes the following string <wp-json/contact-form-7> [this string is part of the request url address, the full address is https://mywebsite.com/wp-json/contact-form-7/v1/contact-forms/18047]

My question is whether this is a flawed method from a security stand point and if it is, is there a recommended alternative.

Appreciating your feedback

add_filter('rest_authentication_errors', function ($errors) {
    if (!is_wp_error($errors)) { // do nothing if there's already an error
        if ($can_access = is_user_logged_in()) {
            $roles = (array)wp_get_current_user()->roles;
            $can_access = in_array('administrator', $roles); // allows only the Administrator role
            $can_access2 = in_array('editor', $roles); // allows only the editor role
        }
        
        #*** Checking if url is for contact-form
        global $wp;
        $url_home22=home_url( $wp->request );

        if (strpos($url_home22, 'wp-json/contact-form-7')) {
            $contact_form=True;
        }else{
            $contact_form=False;
        }

        #*** If user is admin or editor or if url is contact form then allow access to api, otherwise, deny access

        if (!$can_access and !$can_access2 and $contact_form==False) {
            return new WP_Error('user_not_allowed',
                'Sorry, you are not allowed to access the REST API.',
                array('status' => rest_authorization_required_code())
            );
        }
        
    }

    return $errors;
});

0
The Oracle 1 month 2022-06-06T12:34:16-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse