WordPress JSON Web Token Authentication allows you to do REST API authentication via token. It is a simple, non-complex, and easy to use. This plugin probably is the most convenient way to do JWT Authentication in WordPress. Enable PHP HTTP Authorization Header Shared Hosts Most shared hosts have disabled the HTTP Authorization Header by default. To enable this option you’ll....
WordPress JSON Web Token Authentication allows you to do REST API authentication via token. It is a simple, non-complex, and easy to use.
This plugin probably is the most convenient way to do JWT Authentication in WordPress.
Enable PHP HTTP Authorization Header
Shared Hosts
Most shared hosts have disabled the HTTP Authorization Header by default.
To enable this option you’ll need to edit your .htaccess file by adding the following:
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
WPEngine
To enable this option you’ll need to edit your .htaccess file by adding the following (see this issue):
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
Configuration
Configurate the Secret Key
The JWT needs a secret key to sign the token. This secret key must be unique and never be revealed.
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
Configurate CORs Support
This 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);
Namespace and Endpoints
When the plugin is activated, a new namespace is added.
/jwt-auth/v1
Also, two new POST endpoints are added to this namespace.
/wp-json/jwt-auth/v1/token
/wp-json/jwt-auth/v1/token/validate
Requesting/ Generating Token
/wp-json/jwt-auth/v1/token
To generate token, submit a POST request to this endpoint. With username
and password
as the parameters.
It will validates the user credentials, and returns success response including a token if the authentication is correct or returns an error response if the authentication is failed.
Sample of success response when trying to generate token:
{
"success": true,
"statusCode": 200,
"code": "jwt_auth_valid_credential",
"message": "Credential is valid",
"data": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvcG9pbnRzLmNvdXZlZS5jby5pZCIsImlhdCI6MTU4ODQ5OTE0OSwibmJmIjoxNTg4NDk5MTQ5LCJleHAiOjE1ODkxMDM5NDksImRhdGEiOnsidXNlciI6eyJpZCI6MX19fQ.w3pf5PslhviHohmiGF-JlPZV00XWE9c2MfvBK7Su9Fw",
"id": 1,
"email": "[email protected]",
"nicename": "contactjavas",
"firstName": "Bagus Javas",
"lastName": "Heruyanto",
"displayName": "contactjavas"
}
}
Sample of error response when trying to generate token:
{
"success": false,
"statusCode": 403,
"code": "invalid_username",
"message": "Unknown username. Check again or try your email address.",
"data": []
}
Once you get the token, you must store it somewhere in your application. It can be:
– using cookie
– or using localstorage
– or using a wrapper like localForage or PouchDB
– or using local database like SQLite or Hive
– or your choice based on app you develop 😉
Then you should pass this token as Bearer Authentication header to every API call. The header format is:
Authorization: Bearer your-generated-token
and here’s an example:
"Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvcG9pbnRzLmNvdXZlZS5jby5pZCIsImlhdCI6MTU4ODQ5OTE0OSwibmJmIjoxNTg4NDk5MTQ5LCJleHAiOjE1ODkxMDM5NDksImRhdGEiOnsidXNlciI6eyJpZCI6MX19fQ.w3pf5PslhviHohmiGF-JlPZV00XWE9c2MfvBK7Su9Fw";
The jwt-auth will intercept every call to the server and will look for the authorization header, if the authorization header is present, it will try to decode the token and will set the user according with the data stored in it.
If the token is valid, the API call flow will continue as always.
Whitelisting Endpoints
Every call to the server (except the token creation) will be intercepted. However, you might need to whitelist some endpoints. You can use jwt_auth_whitelist
filter to do it. E.g:
add_filter( 'jwt_auth_whitelist', function ( $endpoints ) {
return array(
'/wp-json/custom/v1/webhook/*',
'/wp-json/custom/v1/otp/*',
'/wp-json/custom/v1/account/check',
'/wp-json/custom/v1/register',
);
} );
Validating Token
You likely don’t need to validate the token your self. The plugin handle it for you like explained above.
But if you want to test or validate the token manually, then send a POST request to this endpoint (don’t forget to set your Bearer Authorization header):
/wp-json/jwt-auth/v1/token/validate
Valid Token Response:
{
"success": true,
"statusCode": 200,
"code": "jwt_auth_valid_token",
"message": "Token is valid",
"data": []
}
Errors
If the token is invalid an error will be returned. Here are some samples of errors:
No Secret Key
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_bad_config",
"message": "JWT is not configurated properly.",
"data": []
}
No HTTP_AUTHORIZATION Header
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_no_auth_header",
"message": "Authorization header not found.",
"data": []
}
Bad Iss
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_bad_iss",
"message": "The iss do not match with this server.",
"data": []
}
Invalid Signature
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_invalid_token",
"message": "Signature verification failed",
"data": []
}
Bad Request
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_bad_request",
"message": "User ID not found in the token.",
"data": []
}
User Not Found
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_user_not_found",
"message": "User doesn't exist",
"data": []
}
Expired Token
{
"success": false,
"statusCode": 403,
"code": "jwt_auth_invalid_token",
"message": "Expired token",
"data": []
}
Available Hooks
JWT Auth is developer friendly and has some filters available to override the default settings.
jwt_auth_cors_allow_headers
The jwt_auth_cors_allow_headers
allows you to modify the available headers when the CORs support is enabled.
Default Value:
'X-Requested-With, Content-Type, Accept, Origin, Authorization'
jwt_auth_iss
The jwt_auth_iss allows you to change the value before the payload is encoded to be a token.
Default Value:
get_bloginfo( 'url' )
jwt_auth_not_before
The jwt_auth_not_before
allows you to change the value before the payload is encoded to be a token.
Default Value:
// Creation time.
time()
jwt_auth_expire
The jwt_auth_expire
allows you to change the value before the payload is encoded to be a token.
Default Value:
time() + (DAY_IN_SECONDS * 7)
jwt_auth_alg
The jwt_auth_alg
allows you to change the supported signing algorithm for your application.
Default Value:
'HS256'
jwt_auth_payload
The jwt_auth_payload
allows you to modify all the payload / token data before being encoded and signed.
Default value:
get_bloginfo('url'),
'iat' => $issued_at,
'nbf' => $not_before,
'exp' => $expire,
'data' => array(
'user' => array(
'id' => $user->ID,
)
)
);
jwt_auth_valid_credential_response
The jwt_auth_valid_credential_response
allows you to modify the valid credential response when generating a token.
Default value:
true,
'statusCode' => 200,
'code' => 'jwt_auth_valid_credential',
'message' => __( 'Credential is valid', 'jwt-auth' ),
'data' => array(
'token' => $token,
'id' => $user->ID,
'email' => $user->user_email,
'nicename' => $user->user_nicename,
'firstName' => $user->first_name,
'lastName' => $user->last_name,
'displayName' => $user->display_name,
),
);
jwt_auth_valid_token_response
The jwt_auth_valid_token_response allows you to modify the valid token response when validating a token.
Default value:
true,
'statusCode' => 200,
'code' => 'jwt_auth_valid_token',
'message' => __( 'Token is valid', 'jwt-auth' ),
'data' => array(),
)
);
Usage example:
add_filter('jwt_auth_valid_token_response', function ($response, $user, $token, $payload) {
// Modify the response here.
return $response;
}, 10, 4);
Credits
PHP-JWT from firebase
JWT Authentication for WP REST API
Be Part of the Conversation with WordPress Enthusiasts
Using JWT Auth? Great, join the conversation now!
Let’s talk about overall quality, ease of use, stellar support, unbeatable value, and the amazing experience JWT Auth brings to you.