WordPress.org

Portugal

  • Temas
  • Plugins
  • Notícias
  • Suporte
  • Sobre
  • Padrões
    • Equipa
    • Colaborar
  • Traduções
  • Obter o WordPress
Obter o WordPress
WordPress.org

Plugin Directory

JWT Authentication for WP REST API

  • Submeter um plugin
  • Os meus favoritos
  • Iniciar sessão
  • Submeter um plugin
  • Os meus favoritos
  • Iniciar sessão

JWT Authentication for WP REST API

Por tmeister
Descarregar
  • Detalhes
  • Avaliações
  • Instalação
  • Desenvolvimento
Suporte

Descrição

This plugin seamlessly extends the WP REST API, enabling robust and secure authentication using JSON Web Tokens (JWT). It provides a straightforward way to authenticate users via the REST API, returning a standard JWT upon successful login.

Key features of this free version include:

  • Standard JWT Authentication: Implements the industry-standard RFC 7519 for secure claims representation.
  • Simple Endpoints: Offers clear /token and /token/validate endpoints for generating and validating tokens.
  • Configurable Secret Key: Define your unique secret key via wp-config.php for secure token signing.
  • Optional CORS Support: Easily enable Cross-Origin Resource Sharing support via a wp-config.php constant.
  • Developer Hooks: Provides filters (jwt_auth_expire, jwt_auth_token_before_sign, etc.) for customizing token behavior.

JSON Web Tokens are an open, industry standard method for representing claims securely between two parties.

For users requiring more advanced capabilities such as multiple signing algorithms (RS256, ES256), token refresh/revocation, UI-based configuration, or priority support, consider checking out JWT Authentication PRO.

Support and Requests: Please use GitHub Issues. For priority support, consider upgrading to PRO.

JWT Authentication PRO

Elevate your WordPress security and integration capabilities with JWT Authentication PRO. Building upon the solid foundation of the free version, the PRO version offers advanced features, enhanced security options, and a streamlined user experience:

  • Easy Configuration UI: Manage all settings directly from the WordPress admin area.
  • Token Refresh Endpoint: Allow users to refresh expired tokens seamlessly without requiring re-login.
  • Token Revocation Endpoint: Immediately invalidate specific tokens for enhanced security control.
  • Customizable Token Payload: Add custom claims to your JWT payload to suit your specific application needs.
  • Granular CORS Control: Define allowed origins and headers with more precision directly in the settings.
  • Rate Limiting: Protect your endpoints from abuse with configurable rate limits.
  • Audit Logs: Keep track of token generation, validation, and errors.
  • Priority Support: Get faster, dedicated support directly from the developer.

Upgrade to JWT Authentication PRO Today!

Free vs. PRO Comparison

Here’s a quick look at the key differences:

  • Basic JWT Authentication: Included (Free), Included (PRO)
  • Token Generation: Included (Free), Included (PRO)
  • Token Validation: Included (Free), Included (PRO)
  • Token Refresh Mechanism: Not Included (Free), Included (PRO)
  • Token Revocation: Not Included (Free), Included (PRO)
  • Token Management Dashboard: Not Included (Free), Included (PRO)
  • Analytics & Monitoring: Not Included (Free), Included (PRO)
  • Geo-IP Identification: Not Included (Free), Included (PRO)
  • Rate Limiting: Not Included (Free), Included (PRO)
  • Detailed Documentation: Basic (Free), Comprehensive (PRO)
  • Developer Tools: Not Included (Free), Included (PRO)
  • Premium Support: Community via GitHub (Free), Priority Direct Support (PRO)

REQUIREMENTS

WP REST API V2

This plugin was conceived to extend the WP REST API V2 plugin features and, of course, was built on top of it.

So, to use the wp-api-jwt-auth you need to install and activate WP REST API.

PHP

Minimum PHP version: 7.4.0

PHP HTTP Authorization Header Enable

Most shared hosting providers 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

For WPEngine hosting, you’ll need to edit your .htaccess file by adding the following:

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

See https://github.com/Tmeister/wp-api-jwt-auth/issues/1 for more details.

CONFIGURATION

Configure the Secret Key

The JWT needs a secret key to sign the token. This secret key must be unique and never 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 generate a secure key from: https://api.wordpress.org/secret-key/1.1/salt/

Looking for easier configuration? JWT Authentication PRO allows you to manage all settings through a simple admin UI.

Configure CORS Support

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

To enable 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

Need more functionality? JWT Authentication PRO includes additional endpoints for token refresh and revocation.

USAGE

/wp-json/jwt-auth/v1/token

This is the entry point for JWT Authentication.

It validates the user credentials, username and password, and returns a token to use in future requests to the API if the authentication is correct, or an error if authentication fails.

Sample Request Using AngularJS

(function() {
  var app = angular.module('jwtAuth', []);

  app.controller('MainController', function($scope, $http) {
    var apiHost = 'http://yourdomain.com/wp-json';

    $http.post(apiHost + '/jwt-auth/v1/token', {
      username: 'admin',
      password: 'password'
    })
    .then(function(response) {
      console.log(response.data)
    })
    .catch(function(error) {
      console.error('Error', error.data[0]);
    });
  });
})();

Success Response From The Server

{
  "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9qd3QuZGV2IiwiaWF0IjoxNDM4NTcxMDUwLCJuYmYiOjE0Mzg1NzEwNTAsImV4cCI6MTQzOTE3NTg1MCwiZGF0YSI6eyJ1c2VyIjp7ImlkIjoiMSJ9fX0.YNe6AyWW4B7ZwfFE5wJ0O6qQ8QFcYizimDmBy6hCH_8",
  "user_display_name": "admin",
  "user_email": "[email protected]",
  "user_nicename": "admin"
}

Error Response From The Server

{
  "code": "jwt_auth_failed",
  "data": {
    "status": 403
  },
  "message": "Invalid Credentials."
}

Once you get the token, you must store it somewhere in your application, e.g., in a cookie or using localStorage.

From this point, you should pass this token with every API call.

Sample Call Using The Authorization Header With AngularJS

app.config(function($httpProvider) {
  $httpProvider.interceptors.push(['$q', '$location', '$cookies', function($q, $location, $cookies) {
    return {
      'request': function(config) {
        config.headers = config.headers || {};
        // Assume that you store the token in a cookie
        var globals = $cookies.getObject('globals') || {};
        // If the cookie has the CurrentUser and the token
        // add the Authorization header in each request
        if (globals.currentUser && globals.currentUser.token) {
          config.headers.Authorization = 'Bearer ' + globals.currentUser.token;
        }
        return config;
      }
    };
  }]);
});

The wp-api-jwt-auth plugin 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 to the data stored in it.

If the token is valid, the API call flow will continue as normal.

Sample Headers

POST /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_s9.B5f-4.1JqM

ERRORS

If the token is invalid, an error will be returned. Here are some sample errors:

Invalid Credentials

[
  {
    "code": "jwt_auth_failed",
    "message": "Invalid Credentials.",
    "data": {
      "status": 403
    }
  }
]

Invalid Signature

[
  {
    "code": "jwt_auth_invalid_token",
    "message": "Signature verification failed",
    "data": {
      "status": 403
    }
  }
]

Expired Token

[
  {
    "code": "jwt_auth_invalid_token",
    "message": "Expired token",
    "data": {
      "status": 403
    }
  }
]

Need advanced error tracking? JWT Authentication PRO offers enhanced error tracking and monitoring capabilities.

/wp-json/jwt-auth/v1/token/validate

This is a simple helper endpoint to validate a token. You only need to make a POST request with the Authorization header.

Valid Token Response

{
  "code": "jwt_auth_valid_token",
  "data": {
    "status": 200
  }
}

AVAILABLE HOOKS

The wp-api-jwt-auth plugin is developer-friendly and provides five filters to override the default settings.

jwt_auth_cors_allow_headers

The jwt_auth_cors_allow_headers filter allows you to modify the available headers when CORS support is enabled.

Default Value:

'Access-Control-Allow-Headers, Content-Type, Authorization'

jwt_auth_not_before

The jwt_auth_not_before filter allows you to change the nbf value before the token is created.

Default Value:

Creation time - time()

jwt_auth_expire

The jwt_auth_expire filter allows you to change the exp value before the token is created.

Default Value:

time() + (DAY_IN_SECONDS * 7)

jwt_auth_token_before_sign

The jwt_auth_token_before_sign filter allows you to modify all token data before it is encoded and signed.

Default Value:

$token = array(
    'iss' => get_bloginfo('url'),
    'iat' => $issuedAt,
    'nbf' => $notBefore,
    'exp' => $expire,
    'data' => array(
        'user' => array(
            'id' => $user->data->ID,
        )
    )
);

Want easier customization? JWT Authentication PRO allows you to add custom claims directly through the admin UI.

jwt_auth_token_before_dispatch

The jwt_auth_token_before_dispatch filter allows you to modify the response array before it is sent to the client.

Default Value:

$data = array(
    'token' => $token,
    'user_email' => $user->data->user_email,
    'user_nicename' => $user->data->user_nicename,
    'user_display_name' => $user->data->display_name,
);

jwt_auth_algorithm

The jwt_auth_algorithm filter allows you to modify the signing algorithm.

Default value:

$token = JWT::encode(
    apply_filters('jwt_auth_token_before_sign', $token, $user),
    $secret_key,
    apply_filters('jwt_auth_algorithm', 'HS256')
);

// ...

$token = JWT::decode(
    $token,
    new Key($secret_key, apply_filters('jwt_auth_algorithm', 'HS256'))
);

Testing

I’ve created a small app to test the basic functionality of the plugin. You can get the app and read all the details in the JWT-Client Repo.

Instalação

Using The WordPress Dashboard

  1. Navigate to the ‘Add New’ in the plugins dashboard
  2. Search for ‘jwt-authentication-for-wp-rest-api’
  3. Click ‘Install Now’
  4. Activate the plugin on the Plugin dashboard

Uploading in WordPress Dashboard

  1. Navigate to the ‘Add New’ in the plugins dashboard
  2. Navigate to the ‘Upload’ area
  3. Select jwt-authentication-for-wp-rest-api.zip from your computer
  4. Click ‘Install Now’
  5. Activate the plugin in the Plugin dashboard

Please read our configuration guide to set up the plugin properly.

Perguntas frequentes

Does this plugin support algorithms other than HS256?

The free version only supports HS256. For support for RS256, ES256, and other algorithms, please consider JWT Authentication PRO.

Can I manage settings without editing wp-config.php?

The free version requires editing wp-config.php. JWT Authentication PRO provides a full settings UI within the WordPress admin.

Is there a way to refresh or revoke tokens?

Token refresh and revocation features are available in JWT Authentication PRO.

Where can I get faster support?

Priority support is included with JWT Authentication PRO. For free support, please use the GitHub issues tracker.

How secure is JWT authentication?

JWT authentication is very secure when implemented correctly. Make sure to use a strong secret key and keep it confidential. JWT Auth PRO offers additional security features like rate limiting and token revocation.

Avaliações

Getting an Issue while generating a token at login time

vaibhavk326 7 Maio, 2025 1 resposta
Hi, actually I am trying to generate token at my login time using an wp_login hook but i am unable to do so, can you provide me any way to do it. Tell me whether there is any buildin function is there that I can use. add_action(‘wp_login’, function ($user_login, $user) {if (!user_can($user, ‘dokandar’)) {return;} $response = wp_remote_post(site_url(‘/wp-json/jwt-auth/v1/token’), [ ‘body’ => [ ‘username’ => $user_login, ‘password’ => ‘YOUR_DEFAULT_PASSWORD_IF_AVAILABLE’, // Not ideal, see note below ], ]); if (is_wp_error($response)) { error_log(‘Token request failed: ‘ . $response->get_error_message()); return; } $body = json_decode(wp_remote_retrieve_body($response), true); if (!empty($body[’token’])) { update_user_meta($user->ID, ‘vendor_jwt_token_key’, $body[’token’]); } else { error_log(‘JWT token missing: ‘ . json_encode($body)); } }, 10, 2); I am using this thing but thing is password can’t be accessed directly in wordpress.

Costant message to upgrade to pro

Mwale Kalenga 29 Abril, 2025 1 resposta
There is a constant message in the dashboard that seriously disrupts UX.

Paywall

lavvx5 19 Abril, 2025 1 resposta
Unfortunately, this plugin is (April 2025) behind a paywall. This should be removed from the plugin directory!

Code Error

kklo 22 Setembro, 2024
Hi, I use the Traveler Theme. I installed it according to the instructions, but I always get a connection error: Status Code Error: 401 when connecting with make (integromat)base url: ./domain.com/wp-json/API Key: copied from wp-config.phpHow do I fix this? Thanks

It’s not easy for me to make it work

alexlana 30 Julho, 2024
I can’t find references about how to block endpoints. You can use a code like this: // add user id to the token to store on your front endfunction add_user_id_and_role_to_jwt_response( $data=”, $user=” ) { $data[ ‘user_id’ ] = $user->data->ID; return $data;}add_filter( ‘jwt_auth_token_before_dispatch’, ‘add_user_id_and_role_to_jwt_response’, 10, 2);// create a callback functionfunction token_jwt_permission_callback ( WP_REST_Request $request = null ) { $user_id = sanitize_text_field( $request->get_param( ‘user_id’ ) ); $jwt = new Jwt_Auth(); $jwt_public = new Jwt_Auth_Public( $jwt->get_plugin_name(), $jwt->get_version() ); $user_id_at_token = $jwt_public->determine_current_user( $user_id ); $validate_token = $jwt_public->validate_token( $request ); $valid_token = false; if ( !is_wp_error( $validate_token ) ) { $valid_token = ( $validate_token[ ‘code’ ] === ‘jwt_auth_valid_token’ ); } if ( !$valid_token || $user_id != $user_id_at_token ) { return false; } return true;}// when register your route: register_rest_route( self::get_plugin_namespace(), ‘/get_services’, array( array( ‘methods’ => WP_REST_Server::CREATABLE, ‘callback’ => array( $this, ‘get_services’ ), ‘permission_callback’ => ‘token_jwt_permission_callback’, // <<<<<< set your callback here ) ) );

Simply perfect!

graficowalab 13 Março, 2024
I integrated it with my Flutter app, and it works flawlessly. Here is a little piece of code that I implemented to get User ID and Role: add_filter(‘jwt_auth_token_before_dispatch’, ‘add_user_id_and_role_to_jwt_response’, 10, 2); function add_user_id_and_role_to_jwt_response($data, $user) { // Aggiungi il campo ‘user_id’ al JSON della risposta $data[’user_id’] = $user->data->ID; // Ottieni il ruolo dell’utente $user_roles = $user->roles; $user_role = !empty($user_roles) ? $user_roles[0] : ”; // Aggiungi il campo ‘user_role’ al JSON della risposta $data[’user_role’] = $user_role; // Restituisci il nuovo array dati modificato return $data; }
Ler todas as 49 avaliações

Contribuidores e programadores

“JWT Authentication for WP REST API” é software de código aberto. As seguintes pessoas contribuíram para este plugin:

Contribuidores
  • tmeister

Traduza o “JWT Authentication for WP REST API” para o seu idioma.

Interessado no desenvolvimento?

Consulte o código, consulte o repositório SVN, ou subscreva o registo de alterações por RSS.

Registo de alterações

1.3.6

  • Added Safeguard in enqueue_plugin_assets to Handle Null or Empty $suffix

1.3.5

  • Notice: Add JWT Authentication Pro beta announcement notice.

1.3.4

  • Fix: Skip any type of validation when the authorization header is not Bearer.
  • Feature: Added a setting page to share data and add information about the plugin.

1.3.3

  • Update php-jwt to 6.4.0
  • Fix php warnings (https://github.com/Tmeister/wp-api-jwt-auth/pull/259)
  • Fix the condition where it checks if the request is a REST Request (https://github.com/Tmeister/wp-api-jwt-auth/pull/256)

1.3.2

  • Fix conflicts with other plugins using the same JWT library adding a wrapper namespace to the JWT class.

1.3.1

  • Updating the minimum version of PHP to 7.4
  • Validate the signing algorithm against the supported algorithms @see https://www.rfc-editor.org/rfc/rfc7518#section-3
  • Sanitize the REQUEST_URI and HTTP_AUTHORIZATION values before to use them
  • Use get_header() instead of $_SERVER to get the Authorization header when possible
  • Added typed properties to the JWT_Auth class where possible
  • Along with this release, I release a new simple JWT Client App for testing purposes @see https://github.com/Tmeister/jwt-client

1.3.0

  • Update firebase/php-jwt to 6.3
  • Fix warning, register_rest_route was called incorrectly
  • Allow for Basic Auth, by not attempting to validate Authentication Headers if a valid user has already been determined (see: https://github.com/Tmeister/wp-api-jwt-auth/issues/241)
  • Added a new filter (jwt_auth_algorithm) to allow for customizing the algorithm used for signing the token
  • Props: https://github.com/bradmkjr

1.2.6

  • Cookies && Token compatibility
  • Fix the root problem with gutenberg infinite loops and allow the token validation/generation if the WP cookie exists.
  • More info (https://github.com/Tmeister/wp-api-jwt-auth/pull/138)
  • Props: https://github.com/andrzejpiotrowski

1.2.5

  • Add Gutenberg Compatibility
  • More info (https://github.com/Tmeister/wp-api-jwt-auth/issues/126)

1.2.4

  • Update firebase/php-jwt to v5.0.0 ( https://github.com/firebase/php-jwt )
  • Add Requires PHP Tag

1.2.3

  • Fix Max recursion error in WordPress 4.7 #44

1.2.2

  • Add an extra validation to get the Authorization header
  • Increase determine_current_user priority Fix #13
  • Add the user object as parameter in the jwt_auth_token_before_sign hook
  • Improve error message when auth fails #34
  • Tested with 4.6.1

1.2.0

  • Tested with 4.4.2

1.0.0

  • Initial Release.

Metadados

  • Versão 1.3.7
  • Última actualização Há 2 semanas
  • Instalações activas 60.000+
  • Versão do WordPress 4.2 ou superior
  • Testado até 6.8.0
  • Versão do PHP 7.4.0 ou superior
  • Idioma
    English (US)
  • Etiquetas
    json web authenticationjwtloginwp-apiwp-json
  • Visualização avançada

Classificações

4.3 out of 5 stars.
  • 38 5-star reviews 5 stars 38
  • 2 4-star reviews 4 stars 2
  • 2 3-star reviews 3 stars 2
  • 1 2-star review 2 stars 1
  • 6 1-star reviews 1 star 6

Adicionar a minha avaliação

See all reviews

Contribuidores

  • tmeister

Suporte

Problemas resolvidos nos últimos dois meses:

0 de 3

Ver fórum de suporte

Doar

Gostaria de apoiar o desenvolvimento deste plugin?

Fazer donativo para o plugin

  • Sobre
  • Notícias
  • Hosting
  • Privacidade
  • Showcase
  • Temas
  • Plugins
  • Padrões
  • Aprender
  • Suporte
  • Developers
  • WordPress.tv ↗
  • Get Involved
  • Events
  • Donate ↗
  • Five for the Future
  • WordPress.com ↗
  • Matt ↗
  • bbPress ↗
  • BuddyPress ↗
WordPress.org
WordPress.org

Portugal

  • Visite a nossa página do Facebook
  • Visite a nossa conta X (antigo Twitter)
  • Visit our Mastodon account
  • Visite a nossa conta no Instagram
  • Visite a nossa conta no LinkedIn
  • Visit our YouTube channel
Código é poesia.