New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Basic Authentication not working with WP REST APIv2 #35

Open
rubenhak opened this Issue May 14, 2016 · 69 comments

Comments

Projects
None yet
@rubenhak
Copy link

rubenhak commented May 14, 2016

hi Everybody,

I'm trying to use basic authentication with WP REST API v2 plugin (https://github.com/WP-API/WP-API). But whatever i tried the api returns "Sorry, you are not allowed to ...". Error. I'm using Postman as a client and can see it that correctly set "Authorization" header in the request.

For example if i post here: http://mywebsite.com/wp-json/wp/v2/posts/
Body:
{
"title": "Hello Updated World!",
"content_raw": "Howdy updated content.",
"date": "2013-04-01T14:00:00+10:00"
}

The response is:
{
"code": "rest_cannot_create",
"message": "Sorry, you are not allowed to create new posts.",
"data": {
"status": 401
}
}

I'd appreciate some help here.

Thanks,
Ruben

@navid-dada

This comment has been minimized.

Copy link

navid-dada commented May 14, 2016

+1

@rubenhak

This comment has been minimized.

Copy link

rubenhak commented May 16, 2016

Adding those into .htaccess solves the problem for me:
RewriteCond %{HTTP:Authorization} ^(.)
RewriteRule ^(.
) - [E=HTTP_AUTHORIZATION:%1]

Though, this files gets overwritten every time to edit the plugin.

@rubenhak

This comment has been minimized.

Copy link

rubenhak commented May 17, 2016

Actually this is not a complete solution and more is a workaround. From time to time wordpress overwrites .htaccess files and the changes are lost.

@clemorphy

This comment has been minimized.

Copy link

clemorphy commented Jul 1, 2016

Hi !

Exact same problem for me.

I am using WP REST API v2, and this plugin.
Making a GET request with the Postman Chrome App :
https://website.com/wp-json/wp/v2/users/me

I use Basic Auth with a login / password of one of my editor account.
The Authorization header is added to the request.

And all I get is :

{
  "code": "rest_not_logged_in",
  "message": "You are not currently logged in.",
  "data": {
    "status": 401
  }
}

Adding this to my .htaccess didn't change anything :

RewriteCond %{HTTP:Authorization} ^(.)
RewriteRule ^(.) - [E=HTTP_AUTHORIZATION:%1]

Any idea ?

@michaelnagy

This comment has been minimized.

Copy link

michaelnagy commented Jul 12, 2016

+1

@rubensmz

This comment has been minimized.

Copy link

rubensmz commented Jul 21, 2016

I'm also experiencing same problem. I thought it was due to CGI running on Apache and its inability sometimes to manage with authentication headers. Nevertheless, when I turn to FPM over nginx the problem persists.

@wblaircox

This comment has been minimized.

Copy link

wblaircox commented Aug 4, 2016

+1

1 similar comment
@medrockstar

This comment has been minimized.

Copy link

medrockstar commented Aug 4, 2016

+1

@medrockstar

This comment has been minimized.

Copy link

medrockstar commented Aug 5, 2016

any solution ?

@heikobornholdt

This comment has been minimized.

Copy link

heikobornholdt commented Aug 15, 2016

+1

@ghost

This comment has been minimized.

Copy link

ghost commented Aug 24, 2016

I also have the same issue. Any solutions would be a great help

@Zmimmy

This comment has been minimized.

Copy link

Zmimmy commented Aug 25, 2016

Add this to my .htaccess and it helped:

SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

See WP-API/WP-API#2538 Not ideal but it works.

This https://github.com/WP-API/Basic-Auth/pull/32/files might also be helpful.

@nodeGarden

This comment has been minimized.

Copy link

nodeGarden commented Aug 28, 2016

Have tried both /.htaccess changes, and still getting the same rest_cannot_create error.

PostMan settings:
image

image

image

Results:
image

image

The Service Discovery page (/wp-json/wp/json/) shows that the POST method is created for posts:
image

Fresh install of Wordpress on AWS (Bitnami image if that helps any)
Wordpress: 4.6
WP REST API: Version 2.0-beta13.1 and tried Version 1.2.5
JSON Basic Authentication: Version 0.1

@koenhoeijmakers

This comment has been minimized.

Copy link

koenhoeijmakers commented Sep 1, 2016

Hey guys, after some time i finally found the fix (at least for me), It was a .htaccess issue.

The original .htaccess looked like this:

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

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,

Hope this helps anyone else!

@ethanclevenger91

This comment has been minimized.

Copy link

ethanclevenger91 commented Sep 1, 2016

.htaccess solutions not working for me.

Mine actually works fine on a local version of the site (using either command line curl or Postman) or if I use Postman to post to the live site while logged in in Chrome. Being logged into the dashboard via Chrome seems to go around the REST API authentication, perhaps related to Postman technically being a Chrome app? If I use the "Generate Code" feature in Postman and copy+paste that to CLI, it does not work.

If I try to post to the live site while not logged in in Chrome, I get the "Sorry, you cannot create new posts" error.

@ethanclevenger91

This comment has been minimized.

Copy link

ethanclevenger91 commented Sep 1, 2016

Hm, so local machine, where it works, is running Homestead. The live server, where it was not working, was running PHP 5.5 with cgi as the handler. I bumped it to PHP 5.6, which uses suPHP as the handler, and it now works. This link seems to imply that these .htaccess fixes should resolve this, but I didn't find that to be true. Other thoughts?

@droa6

This comment has been minimized.

Copy link

droa6 commented Sep 8, 2016

Awesome, this solved my issue posting to the Wordpress rest API.
Like @koenhoeijmakers mentioned, the HTTP_AUTHORIZATION rule had to become before all other rules.

@eladm92

This comment has been minimized.

Copy link

eladm92 commented Oct 2, 2016

Had the same issue and the .htaccess solutions did not work for me.
My issue was that apache on CGI tend to change the request headers from 'header' to 'redirect_header'. I've added this to json_basic_auth_handler function

if(isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['REDIRECT_HTTP_AUTHORIZATION'], 6))); }

And it solved my issue

@magadanskiuchen

This comment has been minimized.

Copy link

magadanskiuchen commented Dec 29, 2016

+1 on this

I'm having a similar issue but instead of trying to insert posts I'm simply trying to do a search (which also for some reason requires authentication): /wp-json/wp/v2/posts/?filter[s]=lorem

@monsif

This comment has been minimized.

Copy link

monsif commented Dec 30, 2016

Nothing of these worked for me, i finally added this wonderful plugin that solved all my problems 👍
https://github.com/Tmeister/wp-api-jwt-auth

@wadechandler

This comment has been minimized.

Copy link

wadechandler commented Jan 3, 2017

+1, having the same issue, hosted at GoDaddy on a Linux account. I'm just now trying to investigate, but hoping others trials prove helpful.

@wadechandler

This comment has been minimized.

Copy link

wadechandler commented Jan 3, 2017

I can confirm that koenhoeijmakers .htaccess comment worked for me.

@pie6k

This comment has been minimized.

Copy link

pie6k commented Jan 9, 2017

As WordPress themes developer, I'm not able to force my clients to change their .htaccess file so supplied solution does not apply in my case.

@Harshadraval

This comment has been minimized.

Copy link

Harshadraval commented Feb 11, 2017

its solve that .. for me you can only add a line in .htaccess file is "SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1" . only add line number 4

BEGIN WordPress

RewriteEngine On RewriteBase /demo/goambee/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /demo/goambee/index.php [L]

to

BEGIN WordPress

RewriteEngine On RewriteBase /demo/goambee/ RewriteRule ^index\.php$ - [L] SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /demo/goambee/index.php [L]
@sban90

This comment has been minimized.

Copy link

sban90 commented Feb 20, 2017

I have tried to recommended fixes in this thread with no luck

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

and added these lines to basic-auth.php:
if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':' , base64_decode(substr($_SERVER['REDIRECT_HTTP_AUTHORIZATION'], 6))); }

any other recommendations as to why this is not working? host is running on php 5.6 with fastCGI. Local runs fine but that is on php 7.0 with no CGI

@booberchi

This comment has been minimized.

Copy link

booberchi commented Feb 22, 2017

I too had this problem, and the only thing that worked for me was this plugin: https://github.com/WP-API/Basic-Auth/blob/master/basic-auth.php

Though, it is a shame that this plugin, or any plugin for that matter, is necessary to address this issue. This should be in the core.

@christophwolff

This comment has been minimized.

Copy link

christophwolff commented Aug 10, 2017

It needs a SSL encryption. HTTS

@omzy83

This comment has been minimized.

Copy link

omzy83 commented Aug 10, 2017

@christophwolff how do we do this on local env?

@christophwolff

This comment has been minimized.

Copy link

christophwolff commented Aug 10, 2017

@kepoly

This comment has been minimized.

Copy link

kepoly commented Aug 10, 2017

@christophwolff You don't need HTTPS for this to work.
@omzy83 Are you trying to create a new user?

@omzy83

This comment has been minimized.

Copy link

omzy83 commented Aug 10, 2017

Nope I've just done a simple request in Postman to wp-json/wp/v2/posts

I also tried /wp-json/wp/v2/users/me - which returns rest_not_logged_in

I have installed the Basic Auth plugin and in Postman I've entered the login details.

@christophwolff

This comment has been minimized.

Copy link

christophwolff commented Aug 10, 2017

For me it worked after I had https.

@kamalhussain

This comment has been minimized.

Copy link

kamalhussain commented Aug 22, 2017

In my experience, basic authentication works only with https. I tried modifying .htaccess as explained above but it didn't help with http. However, it started working after I switched to https.

@dambrogia

This comment has been minimized.

Copy link

dambrogia commented Aug 29, 2017

Since I just spent about 5 hours on this, I'll try and save someone the headache. I had 2 issues I ran into:

@eladm92 's issue of CGI renaming the headers. I had my CGI settings within my apache virtual host file. So I commented those lines out:

# AddHandler php7-fastcgi .php
# Action php7-fastcgi /cgi-bin/php.fastcgi

These might also be able to be set within .htaccess files as well depending on your configuration so keep that in mind.

The other problem I ran into was @ethanclevenger91 's problem of not being able to log in while I was logged into chrome. I tried testing it within an incognito browser after making eladm92's fix and everything worked fine.

I also use the basic-auth plugin, but that should be a given.

@datesss

This comment has been minimized.

Copy link

datesss commented Sep 22, 2017

I haven't gotten in working trying the above fixes in this thread (using MAMP on a macbook pro) :-(

@markestocapio

This comment has been minimized.

Copy link

markestocapio commented Dec 5, 2017

For future reference.

If you are using MAMP. The authorization header won't work in the "Individual PHP version for every host (cgi)" mode.

You need to set your PHP to use identical PHP for all hosts.

@eazulay

This comment has been minimized.

Copy link

eazulay commented Feb 9, 2018

Thanks yummish, your solution worked for me too.
I was logged in to WordPress in Firefox and used the RESTClient Firefox plugin in another tab.
As soon as I logged out of WordPress, the RESTClient's requests were being accepted.

@eazulay

This comment has been minimized.

Copy link

eazulay commented Feb 10, 2018

After I logged out of Wordpress my GET requests were accepted. However, all my POST requested came back with error 400 Bad Request - empty request. It turned out I needed to add this header:
Content-Type: application/json

Now it all works as expected.

@XP522038476

This comment has been minimized.

Copy link

XP522038476 commented Mar 14, 2018

@booberchi 我英文不好,我只能用中文写了,我被这个问题恶心到了,我已经研究了5天了任然一无所获,直到看到你提供的插件,我终于可以使用wp_rest_api来链接了,谢谢你,还有就是,这并不是耻辱,至少你帮助了很多人。I proved that this plug-in helped me, thank you booberchi =。=~~~

@NickyBall

This comment has been minimized.

Copy link

NickyBall commented Jun 5, 2018

I fixed this issue by adding RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] directly to httpd-add.conf file in my web server configuration folder. Hope this help.

image

@umyhacker

This comment has been minimized.

Copy link

umyhacker commented Jun 5, 2018

No Solution worked for me

@yuonoda

This comment has been minimized.

Copy link

yuonoda commented Jul 10, 2018

Hey guys, this problem occurs in my environment using Nginx, so I cannot use .htaccess and have to configure conf.d. Does anyone know how to solve it on Nginx server ??

@csimpi

This comment has been minimized.

Copy link

csimpi commented Jul 10, 2018

Our project was in a GoDaddy host, in a day to another the Authorization header just disappeared. I was thinking I made some mistake during the last deployment. After 3 hours of struggling, google-ing, cursing turned out GoDaddy changed something in the server config that stipped the Authorization header. Our users can't use the website at all, and they are still just working on it. Terrible.
So If somebody has any similar mysterious issue, very easy to debug it.

Create a test.php in the webroot folder with this script:

<?php
var_dump(apache_request_headers());
?>

Make sure you have these rules in your .htaccess file

    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Then send a request with any kind of REST tester, set the Authorization header as you wish, then check the result. If you can't find the Authorization header in the result and you have been added the required lines to your .htaccess file, the issue with the web server config that the .htaccess file can't override. Contact your host provider if necessary.

I hope this helps.

@maartenvonkreijfelt

This comment has been minimized.

Copy link

maartenvonkreijfelt commented Jul 10, 2018

Hey guys
I didn't get it done, seemed I used an old version of the plugin :(
This one does work
https://github.com/WP-API/Basic-Auth

@fjarrett

This comment has been minimized.

Copy link

fjarrett commented Jul 11, 2018

@csimpi I can look into that for you (I work at GoDaddy), what’s your URL?

@djabif

This comment has been minimized.

Copy link

djabif commented Jul 11, 2018

Hey guys, I created a tutorial (text+code) to explain how to perform basic wordpress authentication from an Ionic Framework App using the WP REST API. Feel free to download the code and ask me anything. https://ionicthemes.com/tutorials/about/ionic-wordpress-integration

@csimpi

This comment has been minimized.

Copy link

csimpi commented Jul 11, 2018

@fjarrett I sent you an email that I could find on your GitHub profile. Many thanks in advance :)

UPDATE: As Godaddy support works, he is disappeared, still nobody solved our problem, we had to move from Godaddy.

@phantomlution

This comment has been minimized.

Copy link

phantomlution commented Aug 22, 2018

I find a solution. It seems that the auth plugin is not installed properly.
You can download zip -> https://github.com/WP-API/Basic-Auth.git
and then install it. It works for me.
Related to this issue: WP-API/WP-API#3002

@zearg

This comment has been minimized.

Copy link

zearg commented Oct 4, 2018

I didn't need any .htaccess modifications.
Just read this : https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
I forgot to use an "X-WP-Nonce" in wp-json query request headers.

An example code :

In PHP :

wp_enqueue_script( 'test, plugin_dir_url( __FILE__ ) . 'js/test.js', array(), $this->version, false );
wp_localize_script( 'test, 'wpApiSettings', array(
	'root' => esc_url_raw( rest_url() ),
	'nonce' => wp_create_nonce( 'wp_rest' )
));

In JS :

		$.ajax( {
			url: wpApiSettings.root + 'wp/v2/users/me',
			method: 'POST',
			beforeSend: function ( xhr ) {
				xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
			},
			data:{
				'title' : 'Hello Moon'
			}
		} ).done( function ( response ) {
			console.log( response );
		} );

In this example, you can't request directly the WP API in URL.
You have to do this with nonce request headers and auth cookies, in JS on a page or with curl in PHP Code (don't forget auth cookies !)

Hope that'll help

@nhathoangfarmtech

This comment has been minimized.

Copy link

nhathoangfarmtech commented Oct 19, 2018

Hey guys, after some time i finally found the fix (at least for me), It was a .htaccess issue.

The original .htaccess looked like this:

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

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,

Hope this helps anyone else!

Must login to thank you! it works for me!!!

image

@megin1989

This comment has been minimized.

Copy link

megin1989 commented Dec 28, 2018

Hello guys, this problem occurs in Nginx. Does anyone know how to solve it on Nginx server ? Please help me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment