Home » WP API Authentication (JWT)

WP API Authentication (JWT)

Cookie authentication is the standard authentication method included with WordPress.

However, the REST API includes a technique called nonces to avoid CSRF issues. This prevents other sites from forcing you to perform actions without explicitly intending to do so. This requires slightly special handling for the API.

For us to have an API for Mobile Apps, PWA and other JavaScript frameworks, token based authentication is better. It is stateless and does not store any information about our user on the server or in a session.

To add support for alternative modes of authentication, you need to add plugin.
JWT Authentication for WP REST API (https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/).

It extends the WP REST API using JSON Web Tokens Authentication as an authentication method.

Requirements

PHP
Minimum PHP version: 5.3.0

PHP HTTP AUTHORIZATION HEADER ENABLE
Most of the shared hosting has disabled the HTTP Authorization Header by default.

To enable this option you’ll need to edit your .htaccess file adding the follow

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.
)
RewriteRule ^(.) - [E=HTTP_AUTHORIZATION:%1]
To enable this option you’ll need to edit your .htaccess file adding the follow

CONFIGURATION

To add the secret key edit your wp-config.php file and add a new constant called JWT_AUTH_SECRET_KEY

define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key');
You can use a string from here https://api.wordpress.org/secret-key/1.1/salt/

CONFIGURATE CORS SUPPORT
The wp-api-jwt-auth plugin has the option to activate CORs support.

To enable the CORs Support edit your wp-config.php file and add a new constant called JWT_AUTH_CORS_ENABLE

define('JWT_AUTH_CORS_ENABLE', true);
Finally activate the plugin within your wp-admin.

NAMESPACE AND ENDPOINTS
When the plugin is activated, a new namespace is added

/jwt-auth/v1
Also, two new endpoints are added to this namespace

Endpoint | HTTP Verb
/wp-json/jwt-auth/v1/token | POST
/wp-json/jwt-auth/v1/token/validate | POST

USAGE
/WP-JSON/JWT-AUTH/V1/TOKEN
This is the entry point for the JWT Authentication.

Validates the user credentials, username, and password, and returns a token to use in a future request to the API if the authentication is correct or error if the authentication fails.

Leave a Reply