Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WP rest api jwt auth

I would like use WP REST API auth with this plugin : https://github.com/Tmeister/wp-api-jwt-auth

I get the token with this req on POST : http://localhost/wp_rest/wp-json/jwt-auth/v1/token

But I can't do the request for post mehod: localhost/wp_rest/wp-json/wp/v2/posts

I get the error 403:

{
    "code": "rest_forbidden"
    "message": "You don't have permission to do this."
    "data": {
        "status": 403
    }
}

In my header I have this :

Authorization: Bearer
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3RcL3dwX3Jlc3QiLCJpYXQiOjE0NTAzNDEwMTgsIm5iZiI6MTQ1MDM0MTAxOCwiZXhwIjoxNDUwOTQ1ODE4LCJkYXRhIjp7InVzZXIiOnsiaWQiOiIxIn19fQ.rGNPsU4EocClWLYWaSDs1hDJMODszg-eKfqnKSEsiw0

I'm trying with localhost/wp_rest/wp-json/jwt-auth/v1/token/validate but I get this error:

{
    "code": "jwt_auth_no_auth_header",
    "message": "Authorization header not found.",
    "data": {
        "status": 403
    }
}

Any idea?

like image 721
Xavootia Bellion Avatar asked Dec 17 '15 22:12

Xavootia Bellion


People also ask

Is JWT good for API authentication?

JWT-based API auth is a good choice for securing microservices within an organization, or sharing APIs with certain types of external clients. JWT tokens are typically not revokable.


2 Answers

It looks like you did not include Authorization headers in your request. You need to add 'Authorization': 'Bearer PLACE_TOKEN_HERE' in your request headers.

As a sample:

var req = {
    method: 'POST',
    url: window.location.href + 'wp-json/wp/v2/posts',
    headers: {
      'Authorization': 'Bearer ' + TOKEN_GOES_HERE
    }
    data: DATA TO PASS GOES HERE
}
$http(req);
like image 106
Leo Gono Avatar answered Oct 08 '22 03:10

Leo Gono


If the answer provided by Leo Gono and Tunaki still doesn't solve your problem, make sure you've added the following code to your .htaccess if you're using Apache:

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

Make sure to put those lines before the last line with an "[L]" in your .htaccess or else it won't get processed.

It's possible that the Authorisation header gets discarded by server of framework settings. (I've had to change the htaccess for Laravel)

like image 4
Bert H Avatar answered Oct 08 '22 02:10

Bert H