WordPress.org

Nederlands

  • Thema’s
  • Plugins
  • Nieuws
    • Documentatie
    • Forums
  • Over
    • Vertaalproces
    • Stijlgids
    • Onze community
    • Meetups
    • WordCamps
  • Contact
  • WordPress downloaden
WordPress downloaden
WordPress.org

Plugin Directory

JWT Authentication for WP REST API

  • Dien een plugin in
  • Mijn favorieten
  • Login
  • Dien een plugin in
  • Mijn favorieten
  • Login

JWT Authentication for WP REST API

Door tmeister
Download
  • Details
  • Beoordelingen
  • Installatie
  • Ontwikkeling
Ondersteuning

Beschrijving

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)

VEREISTEN

WP REST API V2

Deze plugin is bedacht om de functies van de WP REST API V2 plugin uit te breiden en is daar natuurlijk bovenop gebouwd.

Dus, om de wp-api-jwt-auth te gebruiken moet je WP REST API installeren en activeren.

PHP

Minimum PHP versie: 7.4.0

PHP HTTP autorisatie header inschakelen

De meeste shared hosting providers hebben de HTTP Authorization Header standaard uitgeschakeld.

Om deze optie in te schakelen moet je je .htaccess bestand bewerken en het volgende toevoegen

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.

CONFIGURATIE

De geheime sleutel configureren

Het JWT heeft een geheime sleutel nodig om het token te ondertekenen. Deze geheime sleutel moet uniek zijn en mag nooit worden onthuld.

Om de geheime sleutel toe te voegen bewerk je wp-config.php bestand en voeg een nieuwe constante toe genaamd 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.

Configureren van COR’s ondersteuning

De wp-api-jwt-auth plugin heeft de optie om CORs ondersteuning te activeren.

Om de CORs ondersteuning in te schakelen bewerk je wp-config.php bestand en voeg een nieuwe constante toe genaamd JWT_AUTH_CORS_ENABLE

define('JWT_AUTH_CORS_ENABLE', true);

Activeer tenslotte de plugin in je wp beheer.

Namespace en endpoints

Wanneer de plugin wordt geactiveerd, wordt een nieuwe namespace toegevoegd

/jwt-auth/v1

Ook worden twee nieuwe endpoints toegevoegd aan deze 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.

GEBRUIK

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

Dit is het ingangspunt voor de JWT authenticatie.

Het valideert de gebruiker referenties, gebruikersnaam en wachtwoord, en retourneert een token om te gebruiken in toekomstige aanvragen naar de API als de authenticatie correct is, of een fout als de authenticatie mislukt.

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": "admin@localhost.dev",
  "user_nicename": "admin"
}

Error Response From The Server

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

Zodra je het token hebt, moet je het ergens in je applicatie opslaan, bijvoorbeeld in een cookie of met behulp van localstorage.

Vanaf dit punt moet je dit token doorgeven aan elke API aanroep

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;
      }
    };
  }]);
});

De wp-api-jwt-auth plugin zal elke oproep naar de server onderscheppen en zal zoeken naar de Authorization header. Als de Authorization header aanwezig is, zal het proberen de token te decoderen en de gebruiker instellen volgens de gegevens die erin zijn opgeslagen.

Als het token geldig is, gaat de API aanroep flow door zoals altijd.

Voorbeeld headers

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

FOUTEN

Als het token ongeldig is, wordt een fout gegeven. Hier volgen enkele voorbeelden van fouten:

Ongeldige credentials

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

Ongeldige handtekening

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

Verlopen 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

Dit is een eenvoudig helper endpoint om een token te valideren; je hoeft alleen een POST aanvraag te verzenden met de autorisatie header.

Valid Token Response

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

BESCHIKBARE HOOKS

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

jwt_auth_cors_allow_headers

Met de jwt_auth_cors_allow_headers kan je de beschikbare headers wijzigen wanneer de CORs ondersteuning is ingeschakeld.

Standaardwaarde:

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

jwt_auth_not_before

Het jwt_auth_not_before filter stelt je in staat om de nbf waarde te wijzigen voordat de token wordt aangemaakt.

Standaardwaarde:

Creation time - time()

jwt_auth_expire

Met de jwt_auth_not_before kan je de nbf waarde te wijzigen voordat het token wordt aangemaakt.

Standaardwaarde:

time() + (DAY_IN_SECONDS * 7)

jwt_auth_token_before_sign

Met de jwt_auth_token_before_sign kan je alle tokengegevens wijzigen voordat ze worden gecodeerd en ondertekend.

Standaardwaarde:

$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

Met de jwt_auth_token_before_dispatch kan je toestaan de gehele reactie array wijzigen voordat deze naar de client wordt verzonden.

Standaardwaarde:

$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_algoritme

Met jwt_auth_algorithm kan je het ondertekeningsalgoritme wijzigen.

Standaardwaarde:

$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'))
);

Testen

Ik heb een kleine app gemaakt om de basisfunctionaliteit van de plugin te testen; je kunt de app krijgen en alle details lezen op de JWT-Client repo

Installatie

Het WordPress dashboard gebruiken

  1. Navigeer naar ‘Nieuwe plugin’ in het plugins dashboard
  2. Zoeken naar ‘jwt-authentication-for-wp-rest-api’
  3. Klik op ‘Nu installeren
  4. Activeer de plugin op het plugin dashboard

Uploaden in WordPress dashboard

  1. Navigeer naar ‘Nieuwe plugin’ in het plugins dashboard
  2. Navigeer naar het ‘Upload’ gebied
  3. Selecteer jwt-authentication-for-wp-rest-api.zip van je computer
  4. Klik op ‘Nu installeren
  5. Activeer de plugin in het plugin dashboard

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

FAQ

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.

Beoordelingen

Great plugin!

Mwale Kalenga 15 mei 2025 3 reacties
I’ve been using the plugin for over year, it’s very good and user friendly! At some point there was a constant message to upgrade, but that was fixed.

Upgrade message cannot be removed from my site.

Bizberg Themes 15 mei 2025 1 reactie
Upgrade message cannot be removed from my site.

Getting an Issue while generating a token at login time

vaibhavk326 7 mei 2025 1 reactie
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.

Paywall

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

Code Error

kklo 22 september 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 juli 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 ) ) );
Lees alle 50 beoordelingen

Bijdragers & ontwikkelaars

“JWT Authentication for WP REST API” is open source software. De volgende personen hebben bijgedragen aan deze plugin.

Bijdragers
  • tmeister

Vertaal “JWT Authentication for WP REST API” naar jouw taal.

Interesse in ontwikkeling?

Bekijk de code, haal de SVN repository op, of abonneer je op het ontwikkellog via RSS.

Changelog

1.3.8

  • Fix upsell notice bug, now it is show only one time

1.3.7

  • Added PRO announcement

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 naar 6.4.0
  • PHP waarschuwingen opgelost (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

  • Conflicten oplossen met andere plugins die dezelfde JWT bibliotheek gebruiken door een wrapper namespace toe te voegen aan de JWT klasse.

1.3.1

  • Updaten van de minimum versie van PHP naar 7.4
  • Valideer het ondertekeningsalgoritme aan de hand van de ondersteunde algoritmen @see https://www.rfc-editor.org/rfc/rfc7518#section-3
  • De REQUEST_URI en HTTP_AUTHORIZATION waarden zuiveren alvorens ze te gebruiken
  • Gebruik get_header() in plaats van $_SERVER om de autorisatie header te krijgen wanneer mogelijk
  • Getypte eigenschappen toegevoegd aan de JWT_Auth klasse waar mogelijk
  • Samen met deze release breng ik een nieuwe eenvoudige JWT client app uit voor testdoeleinden @zie https://github.com/Tmeister/jwt-client

1.3.0

  • Firebase/php-jwt naar 6.3 updaten
  • Lost waarschuwing, register_rest_route werd verkeerd aangeroepen op
  • Basic auth toestaan, door niet te proberen authentication headers te valideren als er al een geldige gebruiker is vastgesteld (zie: https://github.com/Tmeister/wp-api-jwt-auth/issues/241)
  • Een nieuw filter toegevoegd (jwt_auth_algorithm) om het algoritme voor het ondertekenen van het token aan te passen toe te staan
  • Met dank aan: https://github.com/bradmkjr

1.2.6

  • Cookies && token compatibiliteit
  • Het Coreprobleem met oneindige lussen in Gutenberg oplossen en de token validatie/generatie toestaan als de WP cookie bestaat.
  • Meer info (https://github.com/Tmeister/wp-api-jwt-auth/pull/138)
  • Met dank aan: https://github.com/andrzejpiotrowski

1.2.5

  • Gutenberg compatibiliteit toevoegen
  • Meer info (https://github.com/Tmeister/wp-api-jwt-auth/issues/126)

1.2.4

  • Update firebase/php-jwt naar v5.0.0 ( https://github.com/firebase/php-jwt )
  • PHP tag toevoegen vereist

1.2.3

  • Max recursiefout oplossen in WordPress 4.7 #44

1.2.2

  • Een extra validatie toevoegen om de autorisatie header te krijgen
  • Verhoog determine_current_user prioriteit fix #13
  • Voeg het gebruikersobject toe als parameter in de jwt_auth_token_before_sign hook
  • Foutbericht verbetert wanneer auth mislukt #34
  • Getest met 4.6.1

1.2.0

  • Getest met 4.4.2

1.0.0

  • Initiële release.

Meta

  • Versie 1.3.8
  • Laatst geüpdatet 3 dagen geleden
  • Actieve installaties 60.000+
  • WordPress versie 4.2 of nieuwer
  • Getest t/m 6.8.1
  • PHP versie 7.4.0 of nieuwer
  • Taal
    English (US)
  • Tags
    json web authenticationjwtloginwp-apiwp-json
  • Geavanceerde weergave

Waarderingen

4.3 van 5 sterren.
  • 39 5 sterren beoordeling 5 sterren 39
  • 2 4 sterren beoordeling 4 sterren 2
  • 2 3 sterren beoordeling 3 sterren 2
  • 1 2 ster beoordeling 2 sterren 1
  • 6 1 sterren beoordeling 1 ster 6

Mijn beoordeling toevoegen

Bekijk alle beoordelingen

Bijdragers

  • tmeister

Ondersteuning

Opgeloste problemen in de laatste twee maanden:

0 van de 3

Het supportforum bekijken

Doneren

Wil je de groei van deze plugin ondersteunen?

Doneer aan deze plugin

  • Over
  • Nieuws
  • Hosting
  • Privacy
  • Showcase
  • Thema's
  • Plugins
  • Patronen
  • Leren
  • Ondersteuning
  • Ontwikkelaars
  • WordPress.tv ↗
  • Raak betrokken
  • Evenementen
  • Doneren ↗
  • Five for the Future
  • WordPress.com ↗
  • Matt ↗
  • bbPress ↗
  • BuddyPress ↗
WordPress.org
WordPress.org

Nederlands

  • Bezoek ons X (voorheen Twitter) account
  • Visit our Bluesky account
  • Bezoek ons Mastodon account
  • Visit our Threads account
  • Onze Facebook pagina bezoeken
  • Bezoek ons Instagram account
  • Bezoek ons LinkedIn account
  • Visit our TikTok account
  • Bezoek ons YouTube kanaal
  • Visit our Tumblr account
Code is poëzie.