Reputation: 157
I've recently picked up some work in which I'll be creating a REST API for my WordPress site, the server requires OAuth 2.0 to authenticate the requests and I'm just wanting to make sure I'm going along the right lines.
The blocks I need to create are for a job search website, the only client user interaction is submitting a form that will apply for the job in question. The rest are simply displaying recently uploaded jobs and pulling in job based on search parameters.
I'm going to start by creating a simple plugin to authenticate the user on page load, there is no login section so there won't be a place where the authentication can take place via user input. I have what I think is the authorisation URL setup so far and I'm going to use Postman to test that it is retrieving data correctly.
Once I have these setup, I'm going to use the plugin to create 3 different functions, one for pulling in the most recent posts, one for searching the server for related posts based on the users criteria, and a final one for posting job application.
Any help regarding any issues with my thinking so far, any problems I might run into, and any supporting docs that you could provide would be greatly appreciated!
Upvotes: 0
Views: 368
Reputation: 551
You can add this code to do authenticates
function json_basic_auth_handler($user){
global $wp_json_basic_auth_error;
$wp_json_basic_auth_error = null;
// Don't authenticate twice
if (!empty($user)) {
return $user;
}
// Check that we're trying to authenticate
if (!isset($_SERVER['PHP_AUTH_USER'])) {
return $user;
}
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
/**
* In multi-site, wp_authenticate_spam_check filter is run on authentication. This filter calls
* get_currentuserinfo which in turn calls the determine_current_user filter. This leads to infinite
* recursion and a stack overflow unless the current function is removed from the determine_current_user
* filter during authentication.
*/
remove_filter('determine_current_user', 'json_basic_auth_handler', 20);
$user = wp_authenticate($username, $password);
add_filter('determine_current_user', 'json_basic_auth_handler', 20);
if (is_wp_error($user)) {
$wp_json_basic_auth_error = $user;
return null;
}
$wp_json_basic_auth_error = true;
return $user->ID;}
function json_basic_auth_error($error)
{
// Passthrough other errors
if (!empty($error)) {
return $error;
}
global $wp_json_basic_auth_error;
return $wp_json_basic_auth_error;
}
add_filter('rest_authentication_errors', 'json_basic_auth_error');````
Upvotes: 1