Authentication for API ensures only trusted users or apps can access your WordPress data safely.
0
0
Authentication for API in Wordpress
Introduction
When you want to let a mobile app securely get or send data to your WordPress site.
When you build a plugin that needs to check user identity before showing private info.
When you want to protect your WordPress REST API from unauthorized access.
When integrating third-party services that need to interact with your WordPress site.
When you want to allow users to log in via external apps using your WordPress credentials.
Syntax
Wordpress
add_action('rest_api_init', function () { register_rest_route('myplugin/v1', '/data', array( 'methods' => 'GET', 'callback' => 'my_callback_function', 'permission_callback' => function () { return is_user_logged_in(); }, )); });
The permission_callback controls who can access the API endpoint.
Use WordPress functions like is_user_logged_in() or check tokens here.
Examples
This example allows only logged-in users with 'read' capability to access the API.
Wordpress
register_rest_route('myplugin/v1', '/data', array( 'methods' => 'GET', 'callback' => 'my_callback_function', 'permission_callback' => function () { return current_user_can('read'); }, ));
This endpoint is public and does not require authentication.
Wordpress
register_rest_route('myplugin/v1', '/public', array( 'methods' => 'GET', 'callback' => 'my_public_callback', 'permission_callback' => '__return_true', ));
This filter blocks all REST API requests from users who are not logged in.
Wordpress
add_filter('rest_authentication_errors', function ($result) { if (!empty($result)) { return $result; } if (!is_user_logged_in()) { return new WP_Error('rest_not_logged_in', 'You must be logged in to access this API.', array('status' => 401)); } return true; });
Sample Program
This code creates a REST API endpoint at /wp-json/example/v1/secret that only logged-in users can access. If you visit this URL while logged in, you get a welcome message. If not logged in, access is denied.
Wordpress
<?php add_action('rest_api_init', function () { register_rest_route('example/v1', '/secret', array( 'methods' => 'GET', 'callback' => function () { return ['message' => 'Hello, authenticated user!']; }, 'permission_callback' => function () { return is_user_logged_in(); }, )); });
OutputSuccess
Important Notes
Always use permission_callback to protect your API routes.
For external apps, consider using OAuth or Application Passwords for safer authentication.
Test your API endpoints with tools like Postman or browser REST clients.
Summary
Authentication keeps your WordPress API secure and private.
Use permission_callback to control access to API routes.
Test and choose the right authentication method for your use case.