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
- Navigeer naar ‘Nieuwe plugin’ in het plugins dashboard
- Zoeken naar ‘jwt-authentication-for-wp-rest-api’
- Klik op ‘Nu installeren
- Activeer de plugin op het plugin dashboard
Uploaden in WordPress dashboard
- Navigeer naar ‘Nieuwe plugin’ in het plugins dashboard
- Navigeer naar het ‘Upload’ gebied
- Selecteer
jwt-authentication-for-wp-rest-api.zip
van je computer - Klik op ‘Nu installeren
- 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
Bijdragers & ontwikkelaars
“JWT Authentication for WP REST API” is open source software. De volgende personen hebben bijgedragen aan deze plugin.
BijdragersVertaal “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.