I'm relatively new to wordpress and am working on a customized site.

I have an API endpoint that I'd like to call to do authentication, because our users are going to have their credentials stored/validated by another application.

For context, API call looks something like this:

$parameters = array('email' => 'email@exampleemail.com', 'password' => 'examplepassword');

    $url = 'https://example.com/api/auth?key=123APIkey' ;
    $data = wp_remote_post($url, array(
        'headers'     => array('Content-Type' => 'application/json; charset=utf-8'),
        'body'        => json_encode($parameters),
        'method'      => 'POST',
        'data_format' => 'body',
    ));

Here are two examples of $data objects which might be returned:

{
"response":200,

"data":{ 
  "email":"sample@someemail.com",
  "first_name":"Jane",
  "last_name":"Doe", 
 } 
}

or if the login failed:

{
  "response": 401,
  "message": "Unauthorized - Invalid credentials"
}

Right now, I have sort of thrown this code into wp-includes/pluggable.php in the wp_authenticate($username, $password) function. But I can't seem to get anything working. How do I properly overwrite the authentication function?

Any help is appreciated and feel free to ask for more information if needed!

Thank you!!

有帮助吗?

解决方案

It's better not to do so. And I'm completely against overriding the default authentication mechanism simply because of WordPress and it's plugins usually are depended on the website's database.

But if you're really into this situation WordPress provides a filter called authenticate:

add_filter( 'authenticate', 'wpse75679_auth', 30, 3 );
function wpse75679_auth( $user, $username, $password ) {
    return $user;
}

Just make sure you're returning an instance of WP_User when your authentication is done.

许可以下: CC-BY-SA归因
scroll top