plugin-icon

JWT Authentication for WP REST API

Door tmeister·
Breidt de WP REST API uit met JSON web tokens authenticatie als authenticatiemethode.
Waardering
4.4/5
Versie
1.4.1
Actieve installaties
60K
Laatst bijgewerkt
Oct 3, 2025
JWT Authentication for WP REST API

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.

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

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)
Gratisop Business abonnement
Door te installeren, ga je akkoord met de Servicevoorwaarden van WordPress.com en de voorwaarden voor plugins van derden.
Getest tot
WordPress 6.8.3
Deze plugin kan worden gedownload, zodat je hem op je kan gebruiken.