Skip to content
Advertisement

How to authenticate the user in the wordpress?

I am creating a plugin. I need to take some informations from rest api of the wordpress, in this link: http://localhost/wordpress/wp-json/wp/v2/posts unfortunately when I try to get some informations from there, my ajax simply do not accept, because only to autheticats users can get informations from there. I tried to use this code:

<?php   

    //I am trying to authenticate the user here
    add_filter( 'rest_authentication_errors', 'only_authorised_rest_access');

    function only_authorised_rest_access( $result )
    {
        if( ! is_user_logged_in() ) {
            return new WP_Error( 'rest_unauthorised', __( 'Only authenticated users can access the REST API.', 'rest_unauthorised' ), array( 'status' => rest_authorization_required_code() ) );
        }

        return $result;
    }
?>

And I am using this function

<?php
function wp_favoritar_posts_init() {
       $post_id = 6;
       
       echo "<div class='redimensionar'>";
       echo "<a id='teste' href='?wpfpaction=add&amp;postid=". $post_id ."' title='teste' rel='nofollow'>Favorito</a>";
       echo "</div>";
       echo "<script>calculate()</script>"; //I am calling the function for take the rest api here
       
   }


   add_shortcode('favorito', 'wp_favoritar_posts_init');


?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
   function calculate(){
       var URL = "http://localhost/wordpress/wp-json/wp/v2/posts";
       
       $.ajax({
           type: "GET",
           dataType: "JSON",
           url: URL,
           success: function(data){
               alert('oi');
           },
           error: function (request, status, error) {
               alert(request.responseText);
           }
       });
       
   }
   
</script>

But when I execute the page in the browser, appear this menssage:

mensseger

Someone has a suggestion to take the cookies from the browser for example for authenticate the user?

Advertisement

Answer

I think you have a plugin installed that restricts the API access. based on the message you have posted.

“Only authenticated users can access the REST API” is not an error message that appears anywhere in WordPress core. Are you using a plugin to restrict access to the API?

example output of plugin error

https://wordpress.org/support/topic/rest-api-not-allowing-unauthenticated-requests/

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement