How to Authenticate WP REST API with JWT Authentication using Fetch API

'Authenticate': 'Basic {what do I put here?}' // Do I need "Basic"?

No, it’s not Basic. It’s Bearer. And the header is Authorization.

So first, obtain a token from /wp-json/jwt-auth/v1/token:

fetch( 'http://example.com/wp-json/jwt-auth/v1/token', {
    method: 'POST',
    body: JSON.stringify( {
        // Username of a user on the WordPress website in which the REST API request
        // is being made to.
        username: 'user',
        // And the above user's password.
        password: 'pass'
    } ),
    headers: {
        'Content-Type': 'application/json'
    }
} )
.then( res => res.json() )
.then( res => console.log( res.token ) );

At this point: .then( res => console.log( res.token ) ), you can cache the token, for example in the browser cookies (document.cookie). I mean, if there were no errors (returned by the REST API endpoint), then the token is stored in res.token.

After you obtained a valid token, you can then use the token when making a request to a REST API endpoint such as Create a Comment — set the Authorization header and set its value to: Bearer <token>, where in the above example, <token> is the value of the res.token.

fetch( 'http://example.com/wp-json/wp/v2/comments', {
    method: 'POST',
    body: JSON.stringify( {
        author_email: '[email protected]',
        author_name: 'Test via REST API',
        content: 'Test comment',
        post: 123
    } ),
    headers: {
        'Content-Type': 'application/json',
        Authorization: 'Bearer <token>'
    }
} )
.then( res => res.json() )
.then( res => console.log( res ) );

Make sure the Authorization header is enabled

Because that header is required by the plugin.

And in my case, the Authorization header (which in PHP can be accessed via $_SERVER['HTTP_AUTHORIZATION']) was missing/disabled, so I had to add this to the Apache’s configuration file (httpd.conf): (requires restarting the Apache server)

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

I did try to add this to the (root) .htaccess file, but it didn’t work for me:

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

I hope that helps you and/or someone else having problems with the Authorization header. 🙂

Resources

Leave a Comment