wordpressrestauthentication

WP REST API and "Only authenticated users can access the REST API"


I have a WordPress: https://example.com I need to use WP REST API.

In .htaccess:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
</IfModule>
# END WordPress

I use theBasic-Auth plugin on my WordPress: https://github.com/WP-API/Basic-Auth

Nevertheless I have:

{
    "code": "rest_cannot_access",
    "message": "Only authenticated users can access the REST API.",
    "data": {
        "status": 401
    }
}

enter image description here

I tested with http and https.

What's wrong?


Solution

  • Solved!

    I changed it to the following

    <IfModule mod_rewrite.c>
    RewriteEngine On
    
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>
    

    The HTTP_AUTHORIZATION rule has to come before the other rules, this is because the L flag exists, the L flag means (last - stop processing rules), because of this it would never come to that rule if it was after the original wordpress rules,