Custom REST API search endpoint with input validation and sanitization. Returns snippet titles, excerpts, and URLs for AJAX search.
Back to Snippets
php
• 65 lines
WordPress Custom REST API Endpoint With JWT Authentication
This code creates a custom WordPress REST API endpoint that requires JWT authentication for access, ideal for securing sensitive data exchanges between the frontend and backend of a WordPress site. You need this when you're building a WordPress application that requires authenticated API requests. The code follows WordPress Coding Standards and includes proper error handling and input validation. It uses the 'jwt-auth' package for handling JSON Web Tokens.
Snippet Stats
Lines
65
Characters
2,185
Read
2 mins
/**
* Custom WordPress REST API endpoint with JWT authentication.
*
* @param WP_REST_Request $request The request object.
* @return WP_REST_Response|WP_Error The response or error object.
* @throws Exception If authentication fails or an error occurs.
*/
function ifci_custom_rest_endpoint( WP_REST_Request $request ) {
// Check if the request is authenticated
if ( ! is_user_logged_in() ) {
return new WP_Error( 'rest_not_authenticated', 'You are not authenticated.', array( 'status' => 401 ) );
}
// Validate the request data
$data = $request->get_json_params();
if ( empty( $data ) || ! is_array( $data ) ) {
return new WP_Error( 'rest_invalid_request', 'Invalid request data.', array( 'status' => 400 ) );
}
// Verify the JWT token
$token = $request->get_header( 'Authorization' );
if ( empty( $token ) ) {
return new WP_Error( 'rest_missing_token', 'Missing JWT token.', array( 'status' => 401 ) );
}
// Authenticate the token
try {
$auth = new JWTAuth();
$user_id = $auth->authenticate( $token );
if ( ! $user_id ) {
throw new Exception( 'Invalid token.' );
}
} catch ( Exception $e ) {
return new WP_Error( 'rest_invalid_token', 'Invalid JWT token.', array( 'status' => 401 ) );
}
// Process the request
try {
// Example processing: retrieve user data
$user = get_user_by( 'id', $user_id );
if ( ! $user ) {
throw new Exception( 'User not found.' );
}
$response = array(
'user_id' => $user->ID,
'username' => $user->user_login,
);
return rest_ensure_response( $response );
} catch ( Exception $e ) {
return new WP_Error( 'rest_error', $e->getMessage(), array( 'status' => 500 ) );
}
}
// Register the custom REST API endpoint
add_action( 'rest_api_init', function () {
register_rest_route( 'ifci/v1', '/custom', array(
'methods' => 'GET',
'callback' => 'ifci_custom_rest_endpoint',
'permission_callback' => function () {
return is_user_logged_in();
},
) );
} );
Found an issue with this snippet? Help us improve by reporting it. Report it →