• Hello .. I want to restrict api access only to logged in users.

    I initially used something like:

    function wpRestApiCannotAccess( $access ) {
    	if( !is_user_logged_in() ) {
    		return new WP_Error( 'rest_cannot_access', __( 'Só usuários autenticados tem acesso a api', 'disable-json-api' ), array( 'status' => rest_authorization_required_code() ) );
    	}
    	return $access;
    }
    add_filter( 'rest_authentication_errors', 'wpRestApiCannotAccess' );

    In an external application, attempting to use ajax and Basic authentication the header with the data does not seem to be sent.

    
    $(document).ready(function(){
        jQuery.ajax({
            async: true,
            crossDomain: true,
            xhrFields: { withCredentials: true },
            url: 'http://xxxx.com/wp-json/wp/v2/tutoriais/?per_page=2',
            method: 'GET',
            timeout: 5000,
            contentType: 'application/json',
            beforeSend: function (xhr) {
                xhr.withCredentials = true;
                xhr.setRequestHeader( 'Authorization', 'Basic aW50ZWdyYWNhbzpBcHBGYWNpbGl0YUludGVncmFsjYW9TaXN0ZW1hQCo=' );
            },
            success: function( response ) {
                console.log(response);
            },
            error: function(){
                console.log('error');
            }
        });
    })
    • This topic was modified 7 years, 10 months ago by raphaelnikson.
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Api only for logged in users’ is closed to new replies.