2

I would like to use the rest API to take a username and a password sent in a request and use it in wp_authenticate() then send back if the credentials were correct. How would I do this.

3
  • You can create a custom endpoint, then in your API request, include the username and password, then call wp_authenticate() in your endpoint to validate the credentials. But the connection should always be using https (secure protocol) because you would be sending plain-text password. And have you actually tried any code, read any tutorials/articles?
    – Sally CJ
    Sep 25, 2021 at 1:47
  • @SallyCJ What method would I use to send the data? Also, what would the function look like?
    – jeffinter
    Sep 25, 2021 at 3:57
  • The API can be used from any application (JS, PHP, cURL, Postman, Python, etc.) by sending basic HTTP requests. E.g. On the front-end (or non admin) side of a WordPress site, you can use the Backbone.js client or wp.apiFetch().
    – Sally CJ
    Sep 25, 2021 at 4:50

3 Answers 3

1

There are 3 ways to authenticate a user using a REST api end-point request,

1- using cookies, which is the way WordPress keeps track of authenticated users in POST requests. You pass the authentication details in your REST request, use the wp_signon() function to sign-in your user, and if successful you set the authentication cookie using wp_set_auth_cookie() function,

$creds = array(
    'user_login'    => 'example',
    'user_password' => 'plaintextpw',
    'remember'      => true
);

$user = wp_signon( $creds, false );

if ( is_wp_error( $user ) ) {
    $msg = $user->get_error_message();
}else{
  wp_clear_auth_cookie();
  wp_set_current_user ( $user->ID ); // Set the current user detail
  wp_set_auth_cookie  ( $user->ID ); // Set auth details in cookie
  $msg = "Logged in successfully"; 
}

You can find a discussion on this WordPress forum thread.

2- Using Basic Authentication requests to your own server

the idea here is that for every REST request you make to your server you pass the user's credentials (every time) over an SSL connection. The WordPress API group provides a plugin on their GitHub repo to do this for you, which allows you to encode the user's credentials and decode it on the other side to authenticate them, so for example, to delete a user's post on the server,

let user='...', pw='...';
jQuery.ajax({
   url: 'http://your-domain/wp-json/wp/v2/posts/50',
   method: 'DELETE',
   crossDomain: true,
   beforeSend: function ( xhr ) {
       xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( user + ':' + pw ) );
   },
   success: function( data, txtStatus, xhr ) {
       console.log( data );
       console.log( xhr.status );
   }
});

For more details see this detailed tutorial

3- using a third party authentication such the open OAuth.

This is what Google uses, and allows your site to identify users based on their Google login credentials. WordPress.com also uses this method for its blog service authentication.

The idea is that your users logs-in a server which identifies them (using cookies on their browser).

Once authenticated, your page (reactive js) makes a request to the authentication authority/server which if confirmed by the user returns an access token which is used to authenticate REST requests going forward.

You could use a third party authentication service, such Google, in which case you can follow this youtube tutorial which walks you through the basics to setting up a Google API project to allow your application to make authentication requests.

Alternatively, you could convert your WordPress server into a OAuth server using an existing plugin such as WP-OAuth Server, and its extensive documentation.

0

The best way to "login" a user on a site is to use the wordpress login form. As other comments and answers suggest, to do it in the way the title of the question implies requires some reinvention of the wheel. The login form in addition to doing the actual login also provides feedback when the login fails and provides a flow to reset the password.

Even if you are going for a fully "headless" wordpress experiance you probably should be 100% sure the effort of reinventing the login form is worth it.

Now if you mean to authenticate user from a different domain it is just not going to work as cookies will be set only on the site's domain IIRC.

So the only valid use case is server to server communication in which you need to store the cookies you recieve from your "login" request and reuse them in the next requests, but this implies you store the user and password on your server in which case using application passwords might actually be a better solution.

3
  • 1
    Doesn't answers the question.
    – Aurovrata
    Dec 28, 2022 at 5:13
  • bad questions get not great answers. In retrospect the OP probably wants to know if a user is logged in but sending a rest request just for that is unlikely to be an optimal way to do it. Dec 28, 2022 at 13:20
  • 1
    unless it is cross domain in which case a whole new can of problems can be created if something like that implemented Dec 28, 2022 at 13:45
0

Add code to functions.php And post data to the route

add_action( 'rest_api_init', 'register_api_hooks' );
// API custom endpoints for WP-REST API
function register_api_hooks() {

    register_rest_route(
        'custom-plugin', '/login/',
        array(
            'methods'  => 'POST',
            'callback' => 'login',
        )
    );
}
    function login() {
        // Your logic goes here.
        return wp_signon( array(
    'user_login'    => $_POST['user_login'],
    'user_password' => $_POST['user_password'],
    'remember'      => $_POST['remember']
), false );

    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.