Uday Blog

Adding JWT In WordPress Rest API

JWT (JSON Web Token) Authentication is a secure method used to authenticate users when accessing the WordPress REST API. Instead of sending the username and password with every request, the user logs in once and receives a token. This token is then used for authenticated API requests.

JWT authentication is commonly used in headless WordPress applications where the frontend is built using technologies like React, Next.js, Vue, mobile apps, or external systems such as Python applications.

Why Use JWT Authentication?

Traditional Basic Authentication sends credentials with every request, which is not ideal for production applications. JWT provides a more secure and scalable approach.

Benefits include:

  • Secure token-based authentication
  • Better integration with React and Next.js applications
  • Suitable for mobile apps and chatbot integrations
  • Supports headless WordPress architecture
  • Avoids exposing WordPress passwords repeatedly
  • Easy integration with Postman and external APIs

How JWT Authentication Works

  • Future API requests include the token in the Authorization header.
  • User sends username and password to the WordPress authentication endpoint.
  • WordPress validates the credentials.
  • A JWT token is generated and returned.
  • The frontend stores the token securely.
1. Install plugin
JWT Authentication for WP REST API
2. Add secret key in wp-config.php

define(‘JWT_AUTH_SECRET_KEY’, ‘your-super-secret-key’);
define(‘JWT_AUTH_CORS_ENABLE’, true);

3. Enable Authorization header (IMPORTANT)
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [E=HTTP_AUTHORIZATION:%1]
4. Generate token

POST request: /wp-json/jwt-auth/v1/token

Body:
{
“username”: “admin”,
“password”: “yourpassword”
}

5. Response

Headers:
Authorization: Bearer YOUR_TOKEN

7. Now authenticated requests work

Example:
GET /wp-json/wp/v2/hospital/474