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.
The latest version of this plugin will soon be released on the WordPress.org plugin repo.
If you are updating from V2.x to V3.x you should familiarise yourself with the upcoming changes to ensure that your site continues to work as you expect it to.
There are two imoportant changes:
See this section of the readme on GitHub
Key changes:
Key changes:
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]
To enable this option you’ll need to edit your .htaccess file by adding the following (see this issue):
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
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
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);
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
/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.
{ "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" } }
{ "success": false, "statusCode": 403, "code": "invalid_username", "message": "Unknown username. Try again or check 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.
Every call to the server (except the token creation some default whitelist) will be intercepted. However, you might need to whitelist some endpoints. You can use jwt_auth_whitelist filter to do it. Please simply add this filter directly (without hook). Or, you can add it to plugins_loaded. Adding this filter inside init (or later) will not work.
If you’re adding the filter inside theme and the whitelisting doesn’t work, please create a small 1 file plugin and add your filter there.
add_filter( 'jwt_auth_whitelist', function ( $endpoints ) { $your_endpoints = array( '/wp-json/custom/v1/webhook/*', '/wp-json/custom/v1/otp/*', '/wp-json/custom/v1/account/check', '/wp-json/custom/v1/register', ); return array_unique( array_merge( $endpoints, $your_endpoints ) ); } );
We whitelist some endpoints by default. This is to prevent error regarding WordPress & WooCommerce. These are the default whitelisted endpoints (without trailing * char):
// Whitelist some endpoints by default (without trailing * char). $default_whitelist = array( // WooCommerce namespace. $rest_api_slug . '/wc/', $rest_api_slug . '/wc-auth/', $rest_api_slug . '/wc-analytics/', // WordPress namespace. $rest_api_slug . '/wp/v2/', );
You might want to remove or modify the existing default whitelist. You can use jwt_auth_default_whitelist filter to do it. Please simply add this filter directly (without hook). Or, you can add it to plugins_loaded. Adding this filter inside init (or later) will not work.
If you’re adding the filter inside theme and the it doesn’t work, please create a small 1 file plugin and add your filter there. It should fix the issue.
add_filter( 'jwt_auth_default_whitelist', function ( $default_whitelist ) { // Modify the $default_whitelist here. return $default_whitelist; } );
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
{ "success": true, "statusCode": 200, "code": "jwt_auth_valid_token", "message": "Token is valid", "data": [] }
If the token is invalid an error will be returned. Here are some samples of errors:
{ "success": false, "statusCode": 403, "code": "jwt_auth_bad_config", "message": "JWT is not configured properly.", "data": [] }
{ "success": false, "statusCode": 403, "code": "jwt_auth_no_auth_header", "message": "Authorization header not found.", "data": [] }
{ "success": false, "statusCode": 403, "code": "jwt_auth_bad_iss", "message": "The iss do not match with this server.", "data": [] }
{ "success": false, "statusCode": 403, "code": "jwt_auth_invalid_token", "message": "Signature verification failed", "data": [] }
{ "success": false, "statusCode": 403, "code": "jwt_auth_bad_request", "message": "User ID not found in the token.", "data": [] }
{ "success": false, "statusCode": 403, "code": "jwt_auth_user_not_found", "message": "User doesn't exist", "data": [] }
{ "success": false, "statusCode": 403, "code": "jwt_auth_invalid_token", "message": "Expired token", "data": [] }
JWT Auth is developer friendly and has some filters available to override the default settings.
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'
Usage example:
/** * Change the allowed CORS headers. * * @param string $headers The allowed headers. * @return string The allowed headers. */ add_filter( 'jwt_auth_cors_allow_headers', function ( $headers ) { // Modify the headers here. return $headers; } );
The jwt_auth_iss allows you to change the iss value before the payload is encoded to be a token.
Default Value:
get_bloginfo( 'url' )
Usage example:
/** * Change the token issuer. * * @param string $iss The token issuer. * @return string The token issuer. */ add_filter( 'jwt_auth_iss', function ( $iss ) { // Modify the "iss" here. return $iss; } );
The jwt_auth_not_before allows you to change the nbf value before the payload is encoded to be a token.
Default Value:
// Creation time. time()
Usage example:
/** * Change the token's nbf value. * * @param int $not_before The default "nbf" value in timestamp. * @param int $issued_at The "iat" value in timestamp. * * @return int The "nbf" value. */ add_filter( 'jwt_auth_not_before', function ( $not_before, $issued_at ) { // Modify the "not_before" here. return $not_before; }, 10, 2 );
The jwt_auth_expire allows you to change the value exp before the payload is encoded to be a token.
Default Value:
time() + (DAY_IN_SECONDS * 7)
Usage example:
/** * Change the token's expire value. * * @param int $expire The default "exp" value in timestamp. * @param int $issued_at The "iat" value in timestamp. * * @return int The "nbf" value. */ add_filter( 'jwt_auth_expire', function ( $expire, $issued_at ) { // Modify the "expire" here. return $expire; }, 10, 2 );
The jwt_auth_alg allows you to change the supported signing algorithm for your application.
Default Value:
'HS256'
Usage example:
/** * Change the token's signing algorithm. * * @param string $alg The default supported signing algorithm. * @return string The supported signing algorithm. */ add_filter( 'jwt_auth_alg', function ( $alg ) { // Change the signing algorithm here. return $alg; } );
The jwt_auth_payload allows you to modify all the payload / token data before being encoded and signed.
Default value:
<?php $token = array( 'iss' => get_bloginfo('url'), 'iat' => $issued_at, 'nbf' => $not_before, 'exp' => $expire, 'data' => array( 'user' => array( 'id' => $user->ID, ) ) );
Usage example:
/** * Modify the payload/ token's data before being encoded & signed. * * @param array $payload The default payload * @param WP_User $user The authenticated user. * . * @return array The payload/ token's data. */ add_filter( 'jwt_auth_payload', function ( $payload, $user ) { // Modify the payload here. return $payload; }, 10, 2 );
The jwt_auth_valid_credential_response allows you to modify the valid credential response when generating a token.
Default value:
<?php $response = array( 'success' => 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, ), );
Usage example:
/** * Modify the response of valid credential. * * @param array $response The default valid credential response. * @param WP_User $user The authenticated user. * . * @return array The valid credential response. */ add_filter( 'jwt_auth_valid_credential_response', function ( $response, $user ) { // Modify the response here. return $response; }, 10, 2 );
The jwt_auth_valid_token_response allows you to modify the valid token response when validating a token.
Default value:
<?php $response = array( 'success' => true, 'statusCode' => 200, 'code' => 'jwt_auth_valid_token', 'message' => __( 'Token is valid', 'jwt-auth' ), 'data' => array(), );
Usage example:
/** * Modify the response of valid token. * * @param array $response The default valid token response. * @param WP_User $user The authenticated user. * @param string $token The raw token. * @param array $payload The token data. * . * @return array The valid token response. */ add_filter( 'jwt_auth_valid_token_response', function ( $response, $user, $token, $payload ) { // Modify the response here. return $response; }, 10, 4 );
The jwt_auth_extra_token_check allows you to add extra criterias to validate the token. If empty, has no problem to proceed. Use empty value to bypass the filter. Any other value will block the token access and returns response with code jwt_auth_obsolete_token.
Default value:
''
Usage example:
/** * Modify the validation of token. No-empty values block token validation. * * @param array $response An empty value ''. * @param WP_User $user The authenticated user. * @param string $token The raw token. * @param array $payload The token data. * . * @return array The valid token response. */ add_filter( 'jwt_auth_extra_token_check', function ( $response, $user, $token, $payload ) { // Modify the response here. return $response; }, 10, 4 );
PHP-JWT from firebase
JWT Authentication for WP REST API
Devices utility by pesseba
The awesome maintainers and contributors
Starting from $0 per month.
Rating
Reviewers
22 reviews
Tags
Developed By
Bagus
Quick & Easy
Common Ninja has a large selection of powerful Wordpress plugins that are easy to use, fully customizable, mobile-friendly and rich with features — so be sure to check them out!
Testimonial plugins for Wordpress
Galleries plugins for Wordpress
SEO plugins for Wordpress
Contact Form plugins for Wordpress
Forms plugins for Wordpress
Social Feeds plugins for Wordpress
Social Sharing plugins for Wordpress
Events Calendar plugins for Wordpress
Sliders plugins for Wordpress
Analytics plugins for Wordpress
Reviews plugins for Wordpress
Comments plugins for Wordpress
Portfolio plugins for Wordpress
Maps plugins for Wordpress
Security plugins for Wordpress
Translation plugins for Wordpress
Ads plugins for Wordpress
Video Player plugins for Wordpress
Music Player plugins for Wordpress
Backup plugins for Wordpress
Privacy plugins for Wordpress
Optimize plugins for Wordpress
Chat plugins for Wordpress
Countdown plugins for Wordpress
Email Marketing plugins for Wordpress
Tabs plugins for Wordpress
Membership plugins for Wordpress
popup plugins for Wordpress
SiteMap plugins for Wordpress
Payment plugins for Wordpress
Coming Soon plugins for Wordpress
Ecommerce plugins for Wordpress
Customer Support plugins for Wordpress
Inventory plugins for Wordpress
Video Player plugins for Wordpress
Testimonials plugins for Wordpress
Tabs plugins for Wordpress
Social Sharing plugins for Wordpress
Social Feeds plugins for Wordpress
Slider plugins for Wordpress
Reviews plugins for Wordpress
Portfolio plugins for Wordpress
Membership plugins for Wordpress
Forms plugins for Wordpress
Events Calendar plugins for Wordpress
Contact plugins for Wordpress
Comments plugins for Wordpress
Analytics plugins for Wordpress
Common Ninja Apps
Browse our extensive collection of compatible plugins, and easily embed them on any website, blog, online store, e-commerce platform, or site builder.
HIPAA-Compliant, Secure, and Customizable Forms for Any Use
Provide Answers to Common Questions & Improve User Experience With the FAQ Accordion Widget
Unleash Creativity with an Interactive Stop Motion Display Widget
Build Fun and Custom Leaderboards to Boost Competition
Keep Clients Informed & Boost Conversions With the Updates & Announcements Widget
Showcase Employee Feedback with Glassdoor Reviews Widget
Enhance Your Website Visually & Draw Attention to Inspiring Quotes
Engage Users, Boost Leads, and Elevate Conversions Seamlessly
Revolutionize form creation effortlessly
Raise Awareness, Simplify Donations, and Make a Difference
AI-Powered Chat for Instant & Efficient Customer Support
Build Custom Website Sections Effortlessly with Section Builder
More plugins
The Common Ninja Search Engine platform helps website builders find the best site widgets, apps, plugins, tools, add-ons, and extensions! Compatible with all major website building platforms - big or small - and updated regularly, our Search Engine tool provides you with the business tools your site needs!