Handling OPTIONS/preflight Requests in API Authentication

Issue Description: The current implementation checks for authorization headers even when the request method is OPTIONS, which causes issues. Adding a check to return a 200 status code when the request method is OPTIONS will fix this issue. This only occurs when doing GET requests from different origins. (example: http://www.example.com requesting from api.example.com)

Error Response for Missing Authorization Header: The error response for a missing authorization header includes the following details:

  • Status: error
  • Error: MISSING_AUTHORIZATION_HEADER
  • Code: 401
  • Error Description: Authorization header not received. Either the authorization header was not sent or it was removed by your server due to security reasons.

Proposed Solution: Add a check in the code to return a 200 status code when the request method is OPTIONS. This will prevent the unnecessary checking for authorization headers in such cases.

Additional Resource: A helpful image that explains the process can be found at this link.

Solution example code (to be added to the files in (wp-content/plugins/wp-rest-api-authentication/admin/partials/flow)):

if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {

$response = array(

'status' => 'success',

'message' => 'Preflight request accepted.',

'code' => '200',

);

wp_send_json($response, 200);

}

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer