Bird
Raised Fist0
Wordpressframework~10 mins

Authentication for API in Wordpress - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to add basic authentication headers in a WordPress API request.

Wordpress
fetch('https://example.com/wp-json/wp/v2/posts', {
  headers: {
    'Authorization': '[1]'
  }
})
Drag options to blanks, or click blank then click option'
A'Bearer ' + token
B'Basic ' + btoa('username:password')
C'Token ' + apiKey
D'OAuth ' + oauthToken
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Bearer' instead of 'Basic' for basic auth
Not encoding username and password
Using OAuth tokens in basic auth header
2fill in blank
medium

Complete the code to register a REST API route with permission callback in WordPress.

Wordpress
register_rest_route('myplugin/v1', '/data', [
  'methods' => 'GET',
  'callback' => 'myplugin_get_data',
  'permission_callback' => [1]
]);
Drag options to blanks, or click blank then click option'
Afunction() { return false; }
Bfunction() { return true; }
Cfunction() { return is_user_logged_in(); }
Dfunction() { return current_user_can('edit_posts'); }
Attempts:
3 left
💡 Hint
Common Mistakes
Returning true always, which makes endpoint public
Returning false always, blocking access
Not using a function for permission_callback
3fill in blank
hard

Fix the error in the code to correctly verify a JWT token in WordPress REST API authentication.

Wordpress
add_filter('rest_authentication_errors', function($result) {
  if (!empty($result)) {
    return $result;
  }
  $token = getallheaders()['Authorization'] ?? '';
  if ($token && !verify_jwt_token([1])) {
    return new WP_Error('jwt_auth_invalid_token', 'Invalid token', ['status' => 403]);
  }
  return true;
});
Drag options to blanks, or click blank then click option'
A$token
Bexplode(' ', $token)[1]
Ctrim(str_replace('Bearer ', '', $token))
Dsubstr($token, 7)
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the whole header string including 'Bearer '
Not handling missing Authorization header
Using wrong string manipulation to extract token
4fill in blank
hard

Fill both blanks to create a WordPress REST API endpoint that requires a nonce for authentication.

Wordpress
register_rest_route('myplugin/v1', '/secure', [
  'methods' => 'POST',
  'callback' => 'myplugin_secure_callback',
  'permission_callback' => function() {
    return wp_verify_nonce([1], [2]);
  }
]);
Drag options to blanks, or click blank then click option'
Asanitize_text_field($_POST['nonce'])
B'myplugin_nonce'
Csanitize_text_field($_REQUEST['_wpnonce'])
D'wp_rest'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong request field for nonce
Using incorrect action name in wp_verify_nonce
Not sanitizing nonce input
5fill in blank
hard

Fill the blanks to implement OAuth 1.0a authentication in WordPress REST API.

Wordpress
add_filter('rest_pre_dispatch', function($response, $server, $request) {
  $oauth = new OAuthConsumer([1], [2]);
  if (!$oauth->verifyRequest($request)) {
    return new WP_Error('oauth_error', 'Invalid OAuth signature', ['status' => 401]);
  }
  return $response;
}, 10, 3);
Drag options to blanks, or click blank then click option'
A'consumer_key_here'
B'consumer_secret_here'
C'access_token_here'
D'access_token_secret_here'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up consumer and access tokens
Not passing correct parameters to OAuthConsumer
Ignoring OAuth verification errors

Practice

(1/5)
1. What is the main purpose of permission_callback in WordPress REST API authentication?
easy
A. To format the API response data
B. To define the URL of the API endpoint
C. To register a new API route
D. To check if the user has permission to access the API endpoint

Solution

  1. Step 1: Understand the role of permission_callback

    This callback function is used to verify if the current user has the right permissions to access a specific API route.
  2. Step 2: Differentiate from other API registration parts

    Other parts like route URL and response formatting are handled separately; permission_callback specifically controls access.
  3. Final Answer:

    To check if the user has permission to access the API endpoint -> Option D
  4. Quick Check:

    permission_callback controls access permission [OK]
Hint: Remember permission_callback controls access rights [OK]
Common Mistakes:
  • Confusing permission_callback with route registration
  • Thinking permission_callback formats data
  • Assuming permission_callback sets URL
2. Which of the following is the correct way to register a REST API route with authentication in WordPress?
easy
A. register_rest_route('myplugin/v1', '/data', array('methods' => 'GET', 'callback' => 'get_data', 'permission_callback' => '__return_true'))
B. register_rest_route('myplugin/v1', '/data', array('methods' => 'GET', 'callback' => 'get_data'))
C. register_rest_route('myplugin/v1', '/data', array('methods' => 'GET', 'callback' => 'get_data', 'auth_callback' => '__return_true'))
D. register_rest_route('myplugin/v1', '/data', array('methods' => 'GET', 'callback' => 'get_data', 'permission' => '__return_true'))

Solution

  1. Step 1: Identify the correct parameter for authentication

    The correct parameter to control access is permission_callback, which should be set to a callable that returns true or false.
  2. Step 2: Check the syntax of the registration function

    register_rest_route('myplugin/v1', '/data', array('methods' => 'GET', 'callback' => 'get_data', 'permission_callback' => '__return_true')) correctly includes permission_callback with a valid callable __return_true allowing access.
  3. Final Answer:

    register_rest_route('myplugin/v1', '/data', array('methods' => 'GET', 'callback' => 'get_data', 'permission_callback' => '__return_true')) -> Option A
  4. Quick Check:

    Use permission_callback for authentication [OK]
Hint: Use permission_callback, not auth_callback or permission [OK]
Common Mistakes:
  • Using 'auth_callback' instead of 'permission_callback'
  • Omitting permission_callback entirely
  • Using 'permission' instead of 'permission_callback'
3. Given this code snippet, what will be the output when an unauthenticated user tries to access the API?
register_rest_route('myplugin/v1', '/secret', array(
  'methods' => 'GET',
  'callback' => 'get_secret_data',
  'permission_callback' => function() {
    return current_user_can('read');
  }
));

function get_secret_data() {
  return 'Secret Info';
}
medium
A. Returns a 401 Unauthorized error
B. Returns a 404 Not Found error
C. Returns an empty string
D. Returns 'Secret Info' to everyone

Solution

  1. Step 1: Understand the permission_callback logic

    The callback checks if the user has the 'read' capability. Unauthenticated users do not have this capability, so it returns false.
  2. Step 2: Know WordPress REST API behavior on permission failure

    If permission_callback returns false, the API returns a 401 Unauthorized error to block access.
  3. Final Answer:

    Returns a 401 Unauthorized error -> Option A
  4. Quick Check:

    Permission denied returns 401 error [OK]
Hint: Permission callback false means 401 error [OK]
Common Mistakes:
  • Assuming data is returned without permission
  • Confusing 401 Unauthorized with 404 Not Found
  • Thinking empty string is returned on failure
4. Identify the error in this WordPress REST API route registration code:
register_rest_route('myplugin/v1', '/info', array(
  'methods' => 'GET',
  'callback' => 'get_info',
  'permission_callback' => 'current_user_can('read')'
));

function get_info() {
  return 'Info';
}
medium
A. The callback function 'get_info' is missing parameters
B. The 'methods' value should be an array, not a string
C. The 'permission_callback' should be a callable, not a function call string
D. The route namespace 'myplugin/v1' is invalid

Solution

  1. Step 1: Check the type of permission_callback

    permission_callback must be a callable function, not the result of a function call. Here, 'current_user_can('read')' is a string calling the function immediately, which is incorrect.
  2. Step 2: Correct usage of permission_callback

    It should be a callable like a function name or anonymous function that returns a boolean when called by the API.
  3. Final Answer:

    The 'permission_callback' should be a callable, not a function call string -> Option C
  4. Quick Check:

    permission_callback must be callable, not called [OK]
Hint: permission_callback needs a callable, not a called function [OK]
Common Mistakes:
  • Passing function call result instead of callable
  • Using string with quotes incorrectly
  • Confusing methods string vs array
5. You want to create a WordPress REST API endpoint that only logged-in users with the 'edit_posts' capability can access. Which of these permission_callback implementations correctly enforces this?
hard
A. permission_callback => function() { return is_user_logged_in(); }
B. permission_callback => function() { return is_user_logged_in() && current_user_can('edit_posts'); }
C. permission_callback => function() { return current_user_can('read'); }
D. permission_callback => function() { return true; }

Solution

  1. Step 1: Understand the requirement

    The endpoint must allow only logged-in users who have the 'edit_posts' capability.
  2. Step 2: Analyze each permission_callback

    permission_callback => function() { return is_user_logged_in() && current_user_can('edit_posts'); } checks both if the user is logged in and if they have the capability, fulfilling the requirement exactly.
  3. Step 3: Why other options fail

    A only checks login without the 'edit_posts' capability. B checks current_user_can('read') which many users have but not 'edit_posts'. D allows everyone.
  4. Final Answer:

    permission_callback => function() { return is_user_logged_in() && current_user_can('edit_posts'); } -> Option B
  5. Quick Check:

    Check login and capability together [OK]
Hint: Check both login and capability for secure access [OK]
Common Mistakes:
  • Using wrong capability like 'read' instead of 'edit_posts'
  • Checking only login without capability
  • Allowing all users by returning true
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard